<?php
/**
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/*配送模块*/
namespace SDXApi\Controller;
use SDXApi\Service\OrderDistributionTimeService;
use Think\Controller;
use Common\Api\Ali_ossApi;

class DistributionController extends AppController {
    public $pagesize=10;

    public function _initialize($apptoken = '', $apptime = '', $check_uid = false, $session_id = '',$check_sign=true)
    {
        parent::_initialize($apptoken, $apptime, $check_uid, $session_id,false);
    }

    /*登录*/
    //TODO 用户登录
    public function login(){
        $name=I('post.name');
        if(empty($name)){
            returnApiError('用户名不能为空');
        }
        $password=I('post.password');
        if(empty($password)){
            returnApiError('密码不能为空');
        }
        $admin_user=M('admin_user');
        $ec_salt=$admin_user->field('ec_salt')->where(array('user_name'=>$name))->find();
        if(!empty($ec_salt['ec_salt'])){
            $password=md5(md5($password).$ec_salt['ec_salt']);
        }else{
            $password=md5($password);
        }

        $row=$admin_user->field('user_id,user_name,email,add_time')->where(array('user_name'=>$name,'password'=>$password))->find();
        //dump($admin_user->getlastsql());
        if($row){
            $warehouse_personnel=M('warehouse_personnel');
            $wprow=$warehouse_personnel->field('position,wid,longitude,latitude,status')->where(array('uid'=>$row['user_id'],'status'=>1))->find();

            //dump($wprow);
            if($wprow){


                $phone = I('post.phone');
                $nickname = I('post.nickname');
                //w_log("ss",$phone.":".$nickname);
                if(!empty($phone)){
                    $phone = trim($phone);
                    $data['phone'] = $phone;
                }
                if(!empty($nickname)){
                    $data['name'] = $nickname;
                }
                if(!empty($phone)||!empty($name)){
                    M('warehouse_personnel')->where(array('uid'=>$row['user_id']))->save($data);
                }



                $user_phone = $warehouse_personnel->field('phone,name')->where(array('uid'=>$row['user_id']))->find();
                $row['position']=$wprow['position'];
                $row['wid']=$wprow['wid'];
                $row['longitude']=$wprow['longitude'];
                $row['latitude']=$wprow['latitude'];
                $row['status']=$wprow['status'];
                $row['phone']=$user_phone['phone'];
                $row['name']=$user_phone['name'];
                $company_array = M("distribution_company_user")->where(array("user_id"=>$row['user_id']))->getField("company_id",true);
                if(empty($company_array)){
                    $row['company_id']=0;
                }else{
                    $row['company_id']=implode(",",$company_array);
                }

                $users=array('user'=>$row);
                $ip=get_client_ip();
                //记录登录日志
                $id=$admin_user->where(array('user_id'=>$row['user_id']))->save(array('last_login'=>gmtime(),'last_ip'=>$ip));
                if($id!=false){
                    //dump($wprow['position']);
                    //exit();
                    switch ($wprow['position']){
                        case 1:
                            $log_info = "配货员-APP登录".$user_phone['name']."[".$name."]";
                            break;
                        case 2:
                            //returnApiError("此功能已暂停使用，配送订单请使用bsc配送");
                            $log_info = "配送员-APP登录".$user_phone['name']."[".$name."]";
                            break;
                        case 3:
                            $log_info = "仓管员-APP登录".$user_phone['name']."[".$name."]";
                            break;
                        case 5:
                            $log_info = "楼小二-APP登录".$user_phone['name']."[".$name."]";
                            break;
                        default:
                            returnApiError("无权限登录");
                            break;

                    }
                    $data=array(
                        'log_time'=>gmtime(),
                        'user_id'=>$row['user_id'],
                        'log_info'=>$log_info,
                        'ip_address'=>$ip
                    );
                    M('admin_log')->add($data);
                }
                returnApiSuccess($users,'登录成功');
            }else{
                returnApiError('该用户没有权限登录');
            }
        }else{
            returnApiError('登录失败');
        }
    }

    /**
     * 检查提交账号是否为配送账号
     * rui poptser@foxmail.com 2016-10-11 10:09:19
     * @param $user_id
     */
    private function check_user($user_id){
        $wp=$this->check_warehouse_personnel($user_id,2);
        if(!$wp){
            returnApiError('无此用户/禁用');
            exit();
        }
    }
    /**
     * TODO 修改用户的手机号和用户名
     */
    public function update_name_phone(){

        $user_id = I('post.user_id');
        $phone = I('post.phone');
        $name = I('post.name');

        if(empty($user_id)){
            returnApiError("USER ID 不存在");
        }
        if(empty($phone)||empty($name)){
            returnApiError("手机号/姓名为空");
        }
        $phone = trim($phone);
        $data['phone'] = $phone;
        $data['name'] = $name;
        M('warehouse_personnel')->where(array('uid'=>$user_id))->save($data);
        returnApiSuccess(null,"修改成功");

    }


    /**
     * 获取配送区域（关联待配送列表）
     */
    public function get_area(){
        $user_id=I('post.user_id','intval');
        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $where['wp_userid']=$user_id;
        $where['pay_status']=array("EGT",2);
        $where['order_status']=1;
        $where['shipping_status']=5;
        $wdr_list = M('order_info')->where($where)->getField("wdr_id",true);	//查询所有的配送区域ID
        $wdr_list = array_unique($wdr_list);
        if(count($wdr_list)>0){
            $where_wdr['id']=array("IN",implode(",",$wdr_list));
            $wdr_str = M("warehouse_deliver_region")->where($where_wdr)->field("id,name")->select();
            $all=array(
                "id" => 0,
                "name" => "全部"
            );
            $re_wdr = array_merge($all,$wdr_str);
            returnApiSuccess($re_wdr,"已返回数据");
        }else{
            returnApiError("无订单");
        }
    }




    /*TODO 待配送列表*/
    public function prepare_list(){
        $user_id=I('post.user_id','intval');

        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $wp=$this->check_user($user_id);
        if(!$wp){
            returnApiError('非法用户或者该用户已被禁用');
        }

        $id=I('post.id');	//配货区域ID
        if(!empty($id)){
            $where['wdr_id']=$id;
        }

        $page=I('post.page','intval');
        $where['wp_userid']=$user_id;
        $where['pay_status']=array("EGT",2);
        $where['order_status']=1;
        $where['196_admin_id']=0;
        $where['distribution_company_id']=array("in",array(0,5));
        $where['shipping_status']=5;
        $count=M('order_info')->where($where)->count();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M('order_info')->field('address_id,user_id,order_id,wid,wdr_id,postscript,best_time_start,best_time,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')->where($where)->limit($pagearr['firstpage'].','.$this->pagesize)->order('add_time desc,order_id desc')->select();
        if($list){
            $order_goods=M('order_goods');
            foreach ($list as $k=>$v){
                $country_name=$this->get_region_name($v['country']);
                $province_name=$this->get_region_name($v['province']);
                $city_name=$this->get_region_name($v['city']);
                $district_name=$this->get_region_name($v['district']);
                $list[$k]['address']=$country_name.$province_name.$city_name.$district_name.$v['address'].$v['sign_building'].$v['address_name'];
                $list[$k]['order_time']=date('Y-m-d H:i:s',$v['order_time']+(8*3600));

                $list[$k]['free_single']=M("order_info_free_single")->
                where(array("order_id"=>$v['order_id']))->count();

                $list[$k]['order_remark']=$v['postscript']; //订单备注
                $list[$k]['order_want_time']=date('Y-m-d H:i:s',$v['best_time_start'])."\n".date('Y-m-d H:i:s',$v['best_time']); //预期送达时间
                $list[$k]['order_area']=M("warehouse_deliver_region")->where(array("id"=>$v['wdr_id']))->getField('name'); //配货区域
                $list[$k]['order_store']=M("warehouse")->where(array("id"=>$v['wid']))->getField('name'); //配货区域
                $list[$k]['weight']=$this->get_order_weight($v['order_id']); //订单重量


                $user_tag = M()->field('k.name,v.value')->
                table('sdx_user_tag_value as v,sdx_user_tag_key as k')->
                where('v.key_id = k.id and v.uid ='.$list[$k]['user_id']." and v.address_id =".$list[$k]['address_id'])->select();
                if($user_tag){
                    foreach ($user_tag as $value){
                        $list[$k]['member_tag'] .=$value['name'].":".$value['value']."\n";
                    }
                }
                $goods_list = A('Sorting')->sh_goods_list($v['order_id'],$v['wid']);
                if($goods_list){
                    $list[$k]['goods_list']=$goods_list;
                }else{
                    unset($list[$k]);
                }


                $re_goods_list = A('Sorting')->re_goods_list($v['order_id'],$v['wid']);
                if($re_goods_list){
                    $list[$k]['goods_list_back']=$re_goods_list;
                }
            }
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last),'success');
        }else{
            returnApiError('没有数据');
        }

    }

    /*TODO 配送中列表*/
    public function distribute_list(){
        $user_id=I('post.user_id','intval');
        $isAll  =I('post.isAll','intval');
        $latitude  =I('post.latitude');
        $longitude   =I('post.longitude');

        if($isAll==1){
            if(empty($latitude)||empty($longitude)){
                returnApiError("未获取到经纬度");
            }else{
                $now_address = $latitude.",".$longitude;
            }
        }

        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);



        //获取群组中的配送订单
        $map = array('g.status'=>1,'g.user_id'=>$user_id);
        $deliver_order_group = D('warehouse_deliver_order_group');
        $group_orders = $deliver_order_group->alias('go')->join('left join '.C('DB_PREFIX').'warehouse_deliver_group g on g.group_id = go.group_id')->field('go.order_id as order_id')->where($map)->select();
        $order_ids = array();
        foreach ($group_orders as $order){
            $order_ids[] = $order['order_id'];
        }



        $id=I('post.id');	//配货区域ID
        if(!empty($id)){
            $where['wdr_id']=$id;
        }
        $page=I('post.page','intval');
        $where['wp_userid']=$user_id;
        $where['pay_status']=array("IN","2,3");
        $where['order_status']=5;
        $where['shipping_status']=1;
        $where['196_admin_id']=0;
        //$where['_string']='order_status=5 and shipping_status=1';

        if(count($order_ids)>0){
            $where['order_id'] = array('not in',$order_ids);
        }

        $count=M('order_info')->where($where)->count();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        if($isAll==1){
            $list=M('order_info')->field('address_id,user_id,batch_no,longitude,latitude,sorting_id,wp_userid,order_id,wid,wdr_id,postscript,best_time_start,best_time,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')->where($where)->order('shipping_time desc,order_id desc')->select();
            //dump($list);
        }else{
            $list=M('order_info')->field('address_id,user_id,batch_no,longitude,latitude,sorting_id,wp_userid,order_id,wid,wdr_id,postscript,best_time_start,best_time,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')->where($where)->limit($pagearr['firstpage'].','.$this->pagesize)->order('shipping_time desc,order_id desc')->select();
        }
        $dcount=M('order_info')->where($where)->count();
        if($list){
            foreach ($list as $k=>$v){
                $country_name=$this->get_region_name($v['country']);
                $province_name=$this->get_region_name($v['province']);
                $city_name=$this->get_region_name($v['city']);
                $district_name=$this->get_region_name($v['district']);


                $deploy_info = $this->get_admin_user_name($v['sorting_id']);
                $distribute_info = $this->get_admin_user_name($v['wp_userid']);
                $list[$k]['deploy_name'] = $deploy_info['user_name']; //配货员姓名
                $list[$k]['deploy_phone'] = $deploy_info['phone']; //配货员手机号码
                $list[$k]['distribute_name'] = $distribute_info['user_name']; //配送员姓名
                $list[$k]['distribute_phone'] = $distribute_info['phone']; //配送员手机号码
                $list[$k]['free_single']=M("order_info_free_single")->
                where(array("order_id"=>$v['order_id']))->count();
                $list[$k]['longitude'] = $v['longitude']; //经度
                $list[$k]['latitude'] = $v['latitude']; //纬度

                if($v['batch_no']>0){
                    $order_where_sub = "batch_no ='".$v['batch_no']."' AND TO_DAYS(from_unixtime(best_time)) = TO_DAYS(from_unixtime(".$v['best_time']."))";
                    $order_num=M("order_info")->where($order_where_sub)->count(); //查询是否有分单
                    if($order_num>1){
                        $list[$k]['sub']= 1;
                    }else{
                        $list[$k]['sub']= 0;
                    }
                }else{
                    $list[$k]['sub']= 0;
                }
                $where= "order_id = ".$v['order_id']." and (action_user not like '%[%' and action_user !='buyer' )and action_note !=''";
                $order_action = M("order_action")->where($where)->select();
                foreach ($order_action as $value){
                    $list[$k]['action_remark'] .=$value['action_user']."  ".$value['action_note']."<br/>";
                }

                $user_tag = M()->field('k.name,v.value')->
                table('sdx_user_tag_value as v,sdx_user_tag_key as k')->
                where('v.key_id = k.id and v.uid ='.$list[$k]['user_id']." and v.address_id =".$list[$k]['address_id'])->select();
                if($user_tag){
                    foreach ($user_tag as $value){
                        $list[$k]['member_tag'] .=$value['name'].":".$value['value']."\n";
                    }
                }

                $first_order = M("order_info")->where("order_status !=2 AND 
                    pay_status IN (2,3) AND user_id = {$v['user_id']}")->order("order_id asc")->getField("order_id");
                if($first_order==$v['order_id']){
                    $list[$k]['first_order'] = 1;
                }else{
                    $list[$k]['first_order'] = 0;
                }

                $list[$k]['address']=$country_name.$province_name.$city_name.$district_name.$v['address'].$v['sign_building'].$v['address_name'];
                $list[$k]['order_time']=date('Y-m-d H:i:s',$v['order_time']+(8*3600));
                $list[$k]['order_state']=1;

                $list[$k]['order_remark']=$v['postscript']; //订单备注
                $list[$k]['order_want_time']=date('Y-m-d H:i:s',$v['best_time_start'])."\n".date('Y-m-d H:i:s',$v['best_time']); //预期送达时间
                $list[$k]['order_area']=M("warehouse_deliver_region")->where(array("id"=>$v['wdr_id']))->getField('name'); //配货区域
                $list[$k]['order_store']=M("warehouse")->where(array("id"=>$v['wid']))->getField('name'); //配货区域

                $goods_list = A('Sorting')->sh_goods_list($v['order_id'],$v['wid']);
                if($goods_list){
                    $list[$k]['goods_list']=$goods_list;
                }else{
                    unset($list[$k]);
                }

                $re_goods_list = A('Sorting')->re_goods_list($v['order_id'],$v['wid']);
                if($re_goods_list){
                    $list[$k]['goods_list_back']=$re_goods_list;
                }
            }
            if($isAll==1&&count($list)>1){
                //返回全部数据，且排序
                $new_l_t_array = array();
                foreach ($list as $value){
                    $new_l_t_array[] = $value['latitude'].",".$value['longitude'];
                }
                $new_address_array = auto_planning($now_address,$new_l_t_array);
                $new_list = array();
                foreach ($new_address_array as $value_new){
                    foreach ($list as $value_list){
                        if($value_new == $value_list['latitude'].",".$value_list['longitude']){
                            $new_list[] = $value_list;
                        }
                    }
                }
                $list = $new_list;
                $is_last = 1;
            }


            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count_prepare'=>$dcount),'success');
        }else{
            returnApiError('没有数据',array('count_prepare'=>$dcount));
        }
    }

    /*
     * TODO 配送完列表
     * */
    public function distributed_list(){
        $user_id=I('post.user_id','intval');

        if(!isset($user_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);
        $page=I('post.page','intval');
        $year = I('post.year','intval');
        $month = I('post.month','intval');
        if($year>0 && $month>0){
            $days = date('t', strtotime($year."-".$month));
            $begintime = strtotime($year."-".$month."-1");
            $endtime = strtotime($year."-".$month."-".$days." 23:59:59");

            $where['confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
        }


        $where['wp_userid']=$user_id;
        $where['196_admin_id']=0;
//        $where['pay_status']=array("in","2,3");
//        $where['order_status']=5;
        $where['shipping_status']=2;
        $count=M('order_info')->where($where)->count();
//         $sql = M('order_info')->getLastSql();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }
        $list=M('order_info')->field('address_id,user_id,batch_no,outgo,order_id,wid,wdr_id,postscript,best_time_start,best_time,order_id,order_sn as order_num,order_status as order_state,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,sign_building,address_name')
            ->where($where)->limit($pagearr['firstpage'].','.$this->pagesize)->order('confirm_time desc,order_id desc')->select();
        if($list){
            foreach ($list as $k=>$v){
                $country_name=$this->get_region_name($v['country']);
                $province_name=$this->get_region_name($v['province']);
                $city_name=$this->get_region_name($v['city']);
                $district_name=$this->get_region_name($v['district']);
                $list[$k]['address']=$country_name.$province_name.$city_name.$district_name.$v['address'].$v['sign_building'].$v['address_name'];
                $list[$k]['order_time']=date('Y-m-d H:i:s',$v['order_time']+(8*3600));
                $list[$k]['free_single']=M("order_info_free_single")->
                where(array("order_id"=>$v['order_id']))->count();
                if($v['batch_no']>0){
                    $list[$k]['sub']=M("order_info")->where(array("batch_no"=>$v['batch_no']))->count(); //查询是否有分单
                }else{
                    $list[$k]['sub']= 0;
                }
//        		if($v['order_state'] = 2){
//                    $list[$k]['order_state']=3;
//                }else{
                $list[$k]['order_state']=2;
                //}
                $list[$k]['outgo']=$v['outgo'];
                $list[$k]['order_remark']=$v['postscript']; //订单备注
                $list[$k]['order_want_time']=date('Y-m-d H:i:s',$v['best_time_start'])."\n".date('Y-m-d H:i:s',$v['best_time']); //预期送达时间
                $order_area = M("warehouse_deliver_region")->where(array("id"=>$v['wdr_id']))->getField('name');
                if($order_area){
                    $list[$k]['order_area']= $order_area;//配货区域
                }else{
                    $list[$k]['order_area']= '';//配货区域
                }

                $order_store = M("warehouse")->where(array("id"=>$v['wid']))->getField('name'); //配货区域
                if($order_store){
                    $list[$k]['order_store']= $order_store;//配货区域
                }else{
                    $list[$k]['order_area']= '';//配货区域
                }


                $where= "order_id = ".$v['order_id']." and (action_user not like '%[%' and action_user !='buyer' )and action_note !=''";
                $order_action = M("order_action")->where($where)->select();
                foreach ($order_action as $value){
                    $list[$k]['action_remark'] .=$value['action_user']."  ".$value['action_note']."<br/>";
                }

                $first_order = M("order_info")->where("order_status !=2 AND 
                    pay_status IN (2,3) AND user_id = {$v['user_id']}")->order("order_id asc")->getField("order_id");
                if($first_order==$v['order_id']){
                    $list[$k]['first_order'] = 1;
                }else{
                    $list[$k]['first_order'] = 0;
                }
                $user_tag = M()->field('k.name,v.value')->
                table('sdx_user_tag_value as v,sdx_user_tag_key as k')->
                where('v.key_id = k.id and v.uid ='.$list[$k]['user_id']." and v.address_id =".$list[$k]['address_id'])->select();
                if($user_tag){
                    foreach ($user_tag as $value){
                        $list[$k]['member_tag'] .=$value['name'].":".$value['value']."\n";
                    }
                }
                $goods_list = A('Sorting')->sh_goods_list($v['order_id'],$v['wid']);
                if($goods_list){
                    $list[$k]['goods_list'] = $goods_list;
                }else{
                    //unset($list[$k]);
                }
                $re_goods_list = A('Sorting')->re_goods_list($v['order_id'],$v['wid']);
                if($re_goods_list){
                    $list[$k]['goods_list_back']=$re_goods_list;
                }
            }
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'success');
        }else{
            $list = array();
            $is_last =1;
            $count = 0;
            returnApiSuccess(array('list'=>$list,'is_last'=>$is_last,'count'=>$count),'success');
        }
    }
    private function get_user_wid_identity($user_id){
        //$user_wid = S("swid_".$user_id);
        if(empty($user_wid)){
            $user_wid = M("warehouse_personnel")->where(array("uid"=>$user_id))->getField("wid");
            //S("swid_".$user_id,$user_wid);
        }
        return $user_wid;
    }
    /*TODO 开始配送*/
    public function distribute($order_id=null,$is_r = false){
        $user_id=I('post.user_id','intval');
        if(empty($order_id)){
            $order_id=I('post.order_id','intval');
        }
        if(empty($user_id) || empty($order_id)){
            returnApiError('参数错误');
        }

        $dis_company = array(741,743,746,712,713,689,686,685,682,681,678,555,529,522,469,423);

        $wid = $this->get_user_wid_identity($user_id);
        $this->check_user($user_id);
        //$where['user_id']=$user_id;
        $where['order_id']=$order_id;
        $where['station']=1;    //只能配送已到站的订单
        $where['pay_status']=array("in","2,3");
        $where['order_status']=array("neq","2");
        $where['wid']=$wid;
        $where['push_bsc']=0; //未推送订单
        $where['196_admin_id']=0;
        $where['outgo_id']=array("not in",$dis_company);
        //$where['distribution_company_id']=array("in",array(0,5));
        $list=M('order_info')->field('order_id,order_sn,user_id,order_status,shipping_status,pay_status,mobile,consignee,best_time,best_time_start,pay_time,is_presell,wid')->where($where)->find();
        if($list['order_id']){
            try {
                $data['order_status']=5;
                $data['shipping_status']=1;
                $data['shipping_time']=gmtime();
                $data['wp_userid'] = $user_id;
                $data['station'] = 2; //开始配送 修改到站状态为已出站
                if($is_r){
                    //随机获取的订单 标记
                    $data['is_random_ps'] = 1;
                }
                $id=M('order_info')->where($where)->save($data);
                if($id!=false){
                    $a=array(
                        'order_id'=>$order_id,
                        'user_id'=>$user_id,
                        'order_status'=>5,
                        'shipping_status'=>1,
                        'pay_status'=>$list['pay_status'],
                        'action_note'=>'开始配送',
                        'to_user'=>1
                    );

                    $this->record_diliveryman_log($a);//记录配送员操作日志

                    $remark['phone'] = M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('phone');
                    $name = M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('name');

                    $this->record_logistics($order_id,1,"订单已由:".$name." [ ".$remark['phone']." ] 开始配送");
                    //生成收货验证码


                        //收货时间为30天前的订单将不发送信息
                        $remark['code'] = $this->get_order_receipt_code($order_id);
                        //初始化时区，解决时区不正确的问题
                        date_default_timezone_set('PRC');
                        if($list['best_time_start']==0){
                            if($list['is_presell']==1){
                                $new_best_time = date("Y-m-d",$list['best_time'])." 20:30:00";
                                $list['best_time'] = strtotime($new_best_time)-1;
                                $list['best_time_start'] = strtotime(date("Y-m-d",$list['best_time'])." 10:00:00");
                            }else{
                                $list['best_time_start'] = $list['best_time']-2*3600;
                            }
                        }
                        $datetime = date("Y-m-d",$list['best_time_start']);

                        $remark['best_time'] = $datetime.' '.date("H:i:s",$list['best_time_start']).'-'.date("H:i:s",$list['best_time']);

                        $wechat_param=array();

                        switch($_SERVER['SERVER_NAME']){
                            case 'api.xian3.com':
                                $thisurl='xian3.com';
                                break;
                            case 'api.test.shidexian.com':
                                $thisurl='test.shidexian.com';
                                break;
                            case 'api.shidexian.com':
                                $thisurl='w.shidexian.com';
                                break;
                            default:
                                $thisurl='w.shidexian.com';
                                break;
                        }
                        $oid=$list['user_id'];
                        $Code=md5($oid.'sdx@9999');
                        $goods_name=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->limit(1)->getField("goods_name");
                        $goods_number=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->count();
                        $wechat_param['url']="https://".$thisurl."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$list['order_id']."&utm_source=GZHshipping_start_notice";
                        $wechat_param['first']='尊敬的'.$list['consignee'].'，您所订购的'.$goods_name.'等'.$goods_number.'件商品已经在配送中，预计到达时间为'.$remark['best_time'].'，请保持手机畅通。';
                        $wechat_param['keyword1']=$list['order_sn'];
                        $wechat_param['keyword2']=$name;
                        $wechat_param['keyword3']=$remark['phone'];
                        $wechat_param['remark']=array("您的订单收货码为：[ ".$remark['code']." ],确认收货时请将此码提供给配送员。如代收，请把该码提供给代收人","#FF0000");
                        A("Smsapi")->send_message_api('receipt_verification',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],$remark,'',$wechat_param);

                    returnApiSuccess(array('id'=>$id),'配送订单成功');

                }else{
                    returnApiError('配送订单失败');
                }
            }catch(Exception $e){
                returnApiErrorExample($e->getMessage());
            }
        }else{

            $order_info = M("order_info")->where("order_id = ".$order_id)->find();
            if(in_array($order_info['outgo_id'],$dis_company)) returnApiError("非你所属配送公司订单,此单属于:{$order_info['outgo_id']}");

            if($order_info['wid']!=$wid) returnApiError("非本仓库订单,此单属于仓库:{$order_info['wid']}，您属于：".$wid);
            if($order_info['wp_userid']!=0) returnApiError("已在配送中");
            if($order_info['shipping_status']!=5) returnApiError("订单不在配货完成状态");
            if($order_info['order_status']==2) returnApiError("订单已被取消");
            if($order_info['push_bsc']!=0) returnApiError("订单已被推送到其它平台");
            if($order_info['pay_status']!=2 && $order_info['pay_status']!=3) returnApiError("订单还未支付或已退款");

        }

    }

    /*TODO 配送结束*/
    public function distributed(){
        $user_id=I('post.user_id','intval');
        $order_id=I('post.order_id','intval');
        $verif_code=I('post.verif_code','intval');
        if(!isset($user_id) || !isset($order_id)|| !isset($verif_code)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);


        $verif_code_server = M("order_verif_code")->where(array("order_id"=>$order_id))->getField("code");
        if($verif_code_server){
            if($verif_code_server!=$verif_code){
                returnApiError("收货码不正确！");
            }
        }else{
            returnApiError("未发送收货码，请重新发送");
        }



        //$where['user_id']=$user_id;
        $where['order_id']=$order_id;
        $where['196_admin_id']=0;
        $where['pay_status']=array("in","2,3");
        $where['order_status']=array("neq","2");

        $list=M('order_info')->field('order_id,order_sn,wid,user_id,order_status,shipping_status,pay_status,mobile,consignee,order_amount,money_paid,surplus,best_time')->where($where)->find();
        if($list['order_id']){
            if($list['order_status']==5 && $list['shipping_status']==2){
                returnApiError('此单已确认收货，不用重复确认');
            }
            if($list['shipping_status']!=1){
                returnApiError("订单需要配送员开始配送后才可以确认收货");
            }
            try {
                if($_FILES['photo']['size']>100){
                    $path= "uploads/refund_pic/".rand(10000000,99999999).".".end(explode('.', $_FILES['photo']['name']));
                    Ali_ossApi::upload($path, $_FILES['photo']['tmp_name']);
                }


                $data['order_status']=5;
                $data['shipping_status']=2;
                $data['done_photo']=$path;
                $data['confirm_time']=gmtime();
                $data['wp_userid']=$user_id;
                $id=M('order_info')->where($where)->save($data);
                if($id!=false){
                    $is_shipping_status = M("order_action")->where(array("order_id"=>$order_id,"shipping_status"=>2))->count();
                    if(empty($is_shipping_status)){
                        $this->order_buckle_inventory($list);
                    }
                    $wechat_param=array();

                    switch($_SERVER['SERVER_NAME']){
                        case 'api.xian3.com':
                            $thisurl='xian3.com';
                            break;
                        case 'api.test.shidexian.com':
                            $thisurl='test.shidexian.com';
                            break;
                        case 'api.shidexian.com':
                            $thisurl='w.shidexian.com';
                            break;
                        default:
                            $thisurl='w.shidexian.com';
                            break;
                    }
                    $oid=$list['user_id'];
                    $Code=md5($oid.'sdx@9999');

                    $goods_name=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->limit(1)->getField("goods_name");
                    $goods_number=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->count();

                    $louxiaoer_info=A("Smsapi")->get_louxiaoer_info($list['order_id']);

                    if(!empty($louxiaoer_info['name']) && !empty($louxiaoer_info['phone'])){
                        $housekeeper="";
                    }else{
                        $housekeeper="";
                    }

                    //收货超时红包
                    $overtimeBonus='';
                    $overtimeBonusMessage='';
                    $thirtyMinutes=1800;//秒
                    $bonusNote='';
                    if(strtotime("now")>$list['best_time']+$thirtyMinutes && false==true){
                        $overtimeBonus="订单配送超时给您带来不便，特赔付5元超时红包至您账户，请查收！";
                        $overtimeBonusMessage="订单超时特赔付5元红包至您账户，";
                        $record_id=D("Payment")->recharge_bonus($list['user_id'],C("BONUS_APOLOGIZE"));

                        if(!empty($record_id)){
                            $bonusNote.=' 超时配送返红包//红包序列号：'.implode(",",$record_id);
                        }
                        

                    }

                    $a=array(
                        'order_id'=>$list['order_id'],
                        'user_id'=>$user_id,
                        'order_status'=>5,
                        'shipping_status'=>2,
                        'pay_status'=>$list['pay_status'],
                        'to_user'=>1,
                        'action_note'=>'配送完成,收货确认'.$bonusNote
                    );
                    $this->record_diliveryman_log($a);//记录配送员操作日志
                    $this->record_logistics($list['order_id'],2,"确认收货");

                    //订单超时处理
                    $distribution = new OrderDistributionTimeService();
                    $distribution->add_order_info_overtime($order_id, 2);

                    $wechat_param['url']="https://".$thisurl."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$list['order_id']."&utm_source=GZHorder_finish";
                    $wechat_param['first']='尊敬的'.$list['consignee'].',您所订购的'.$goods_name.'等'.$goods_number.'件商品已经成功送达。'.$overtimeBonus;
                    $wechat_param['keyword1']=$list['order_sn'];
                    $wechat_param['keyword2']=sprintf("%.2f",($list['order_amount']+$list['money_paid']+$list['surplus']));
                    $wechat_param['keyword3']=date("Y-m-d H:i:s");
                    $wechat_param['remark']=$housekeeper;



                    //发送订单配送完成短信给收货人
                    $send_result = A("Smsapi")->send_message_api('order_finish',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],array('overtimeBonus'=>$overtimeBonusMessage),'',$wechat_param);
                    $this->insert_ready_sendmsg_order($list);

                    //确认收货，赠送红包
                    D('Userbonus')->send_bonus_to_user($list['user_id'],$list['order_id']);

                    returnApiSuccess(array('id'=>$id),'收货确认');
                }else{
                    returnApiError('收货失败');
                }
            }catch (Exception $e){
                returnApiErrorExample($e->getMessage());
            }

        }else{
            returnApiError('查无此订单/订单状态不正常');
        }
    }

    /**
     * 保存准备发送短信的已确认订单
     */
    public function insert_ready_sendmsg_order($order){
        $data=array();
        $data['order_id']=$order['order_id'];
        $data['order_sn']=$order['order_sn'];
        $data['consignee']=$order['consignee'];
        $data['uid']=$order['user_id'];
        $data['mobile_phone']=$order['mobile'];
        $data['send_time']=gmtime()+7200;
        $data['is_send']=0;

        M("order_confirm_sendmsg")->data($data)->add();
    }

    /*
     * TODO 收货确认减冻结库存
     * */
    public function order_buckle_inventory($order){

        $is_shipping_status = M("order_action")->where(array("order_id"=>$order['order_id'],"shipping_status"=>array("in",array(2,6))))->count();
        $is_freeze_record = M("goods_freeze_record")->where(array("source_no"=>$order['order_sn'],"record_type"=>6))->count();
        if($is_shipping_status>0||$is_freeze_record>0){
            //在冻库处理中判断二次确认BUG
            return true;
        }


        $wid=$order['wid'];
        $where='(order_id='.$order['order_id'].' and is_presell=0) or (order_id='.$order['order_id'].' and is_presell=1 and buckle_inventory=1)';
        $order_goods=M('order_goods')->where($where)->select();
        if($order_goods){
            $goodsstorage_mod=D('Goodsstorage');
            $goodsfreezerecord=D('Goodsfreezerecord');
            $refund_detail=M('refund_detail');
            $rdgoods=array();
            //检查退货退款时是否已经减掉了冻结库存，若有，该操作则不进行减操作
            $rdlist=$refund_detail->field('goods_id,SUM(refund_number) as refund_number')
                ->where(array('order_id'=>$order['order_id']))
                ->group('goods_id')
                ->select();
            if($rdlist){
                foreach ($rdlist as $key=>$val){
                    $rdgoods[$val['goods_id']]=$val['refund_number'];
                }
            }
            foreach ($order_goods as $k=>$v){
                $gsdata=$goodsstorage_mod->get_warehous_goods($wid,$v['goods_id']);
                if($gsdata){
                    if(!empty($rdgoods[$v['goods_id']])){
                        $refund_number=$rdgoods[$v['goods_id']];
                        $v['goods_number']=$v['goods_number']-ceil($refund_number);
                    }
                    if($v['goods_number']==0){// 过滤订单商品购买数据为0时，不插入冻结库存记录
                        continue;
                    }
                    //减去冻结库存
                    $goodsstorage_mod->save_freeze_theactual_goods($wid,$v['goods_id'],$v['goods_number']);
                    $goodsfreezerecorddata=array(
                        'goods_storage_id'=>$gsdata['id'],
                        'wid'=>$wid,
                        'goods_id'=>$v['goods_id'],
                        'goods_sn'=>$v['goods_sn'],
                        'goods_name'=>$v['goods_name'],
                        'freeze_num'=>$v['goods_number'],
                        'real_num'=>0,
                        'frozen_num'=>$gsdata['freeze_num']-$v['goods_number'],
                        'defective_num'=>0,
                        'operation_userid'=>0,
                        'average_userid'=>$order['user_id'],
                        'operation_addtime'=>gmtime(),
                        'source_no'=>$order['order_sn'],
                        'record_type'=>6,
                        'remark'=>'确认收货',
                    );
                    //生成冻结库存记录
                    $goodsfreezerecord->add_freeze_record($goodsfreezerecorddata);
                }else{
                    continue;
                }
            }
        }else{
            return false;
        }
    }

    /* TODO 扫码条码*/
    public function scanner(){
        $wp_userid=I('post.user_id','intval');
        $order_id=I('post.barcode');
        $order_number=I('post.order_number');   //手动输入的订单号后8位


        if(empty($order_id)){
            if(!isset($wp_userid) || !isset($order_number)){
                if(!is_numeric($order_number)){
                    returnApiError('参数错误');
                }
            }
        }else{
            if(!isset($wp_userid) || !isset($order_id)){
                returnApiError('参数错误');
            }
        }
        $this->check_user($wp_userid);
        //$where['wp_userid']=$wp_userid;

        if(empty($order_id)){
            $where['order_sn']=array("like","%".$order_number);
        }else{
            if(strlen($order_id) > 9){
                //扫出订单ID大于9，按订单编号查询
                if(strlen($order_id) > 19){
                    //扫出订单ID大于19，按订单编号加分袋信息查询
                    $where['order_sn'] = substr($order_id, 0, 19);
                }else{
                    $where['order_sn'] = $order_id;
                }
            }else{
                $where['order_id'] = $order_id;
            }
        }
        $company_array = M("distribution_company_user")->where(array("user_id"=>$wp_userid))->getField("company_id",true);
        if(!empty($company_array)){
            $where['distribution_company_id'] = array("in",$company_array);
        }
        //returnApiError()
        $where['pay_status']=array('EGT',2);
        $where['order_status']=array('neq',2);
        $where['shipping_id']=3;
        $where['196_admin_id']=0;
        $where['outgo']=1;	    //商品已经出仓
        $where['push_bsc']=0; //未推送订单
        //$where['shipping_status']=5;	    //配货已经完成

        $order=M('order_info')->field('station,wid,wdr_id,postscript,best_time_start,best_time,order_id,order_sn as order_num,order_status as order_state,shipping_status,add_time as order_time,consignee as name,mobile as phone,country,province,city,district,address,wp_userid')->where($where)->find();

        //dump(M('order_info')->getlastsql());

        if($order){
            try {
                if($order['wp_userid']==0 || $order['wp_userid']==$wp_userid){
                    $country_name=$this->get_region_name($order['country']);
                    $province_name=$this->get_region_name($order['province']);
                    $city_name=$this->get_region_name($order['city']);
                    $district_name=$this->get_region_name($order['district']);
                    $data['order_id']=$order['order_id'];

                    $data['free_single'] = M("order_info_free_single")->
                    where(array("order_id"=>$order['order_id']))->count();

                    $data['order_num']=$order['order_num'];
                    $data['address']=$country_name.$province_name.$city_name.$district_name.$order['address'];
                    $data['order_time']=date('Y-m-d H:i:s',$order['order_time']+(8*3600));
                    $data['order_remark']=$data['postscript']; //订单备注
                    $data['order_want_time']=date('Y-m-d H:i:s',$order['best_time_start'])."\n".date('Y-m-d H:i:s',$order['best_time']); //预期送达时间
                    $data['order_area']=M("warehouse_deliver_region")->where(array("id"=>$data['wdr_id']))->getField('name'); //配货区域
                    $data['order_store']=M("warehouse")->where(array("id"=>$data['wid']))->getField('name'); //配货区域
                    if($order['order_state'] !=2 && $order['shipping_status']==5 &&$order['station']==0){
                        $data['order_state']=5; //未到站
                    }elseif ($order['order_state'] !=2 && $order['shipping_status']==5&&$order['station']==1){
                        $data['order_state']=0; //待配送
                    }elseif ($order['order_state']!=2 && $order['shipping_status']==1&&$order['station']==2){
                        $data['order_state']=1;  //配送中
                    }elseif($order['order_state']!=2 && $order['shipping_status']==2){
                        $data['order_state']=2;  //收货确认
                    }else{
                        returnApiError('订单不在待配送/配送中/已收货状态');
                    }
// 		        		$orid=M('order_info')->where(array('order_id'=>$order_id))->save(array('wp_userid'=>$wp_userid));
                    $data['station']=$order['station'];
                    $data['phone']=$order['phone'];
                    $data['name']=$order['name'];

                    if($data['batch_no']>0){
                        $order_where_sub = "batch_no =".$data['batch_no']." AND TO_DAYS(from_unixtime(best_time)) = TO_DAYS(from_unixtime(".$data['best_time']."))";
                        $order_num=M("order_info")->where($order_where_sub)->count(); //查询是否有分单
                        if($order_num>1){
                            $data['sub']= 1;
                        }else{
                            $data['sub']= 0;
                        }
                    }else{
                        $data['sub']= 0;
                    }



                    $order_goods=M('order_goods');
                    $goods=$order_goods->field('goods_sn as goods_number,goods_id as id,goods_name as name,goods_price as price,goods_number as `count`')->where(array('order_id'=>$order['order_id']))->select();
                    $data['goods_list']=$goods;

                    $goods_list = A('Sorting')->sh_goods_list($order['order_id'],$order['wid']);
                    if($goods_list){
                        $data['goods_list']=$goods_list;
                    }

                    $re_goods_list = A('Sorting')->re_goods_list($order['order_id'],$order['wid']);
                    if($re_goods_list){
                        $data['goods_list_back']=$re_goods_list;
                    }

                    //M('order_info')->where($where)->save(array('shipping_status'=>1));//修改配送状态为发货中
                    returnApiSuccess(array('distribute'=>$data));
                }else{
                    returnApiError('此单配送员操作->'.M('admin_user')->where(array('user_id'=>$order['wp_userid']))->getField('user_name'));
                }
            }catch (Exception $e){
                returnApiErrorExample($e->getMessage());
            }
        }else{
            returnApiError("骚年，认输吧！\n无法操作此订单");
        }
    }

    /*
     * TODO 配送员定位收集
     * */

    public function position(){
        $user_id=I('post.user_id','intval');
        $longitude=I('post.longitude');
        $latitude=I('post.latitude');
        if(!isset($user_id) || !isset($longitude) || !isset($latitude)){
            returnApiError('参数错误');
        }
        $where['uid']=$user_id;
        $where['status']=1;
        $warehouse_personnel=M('warehouse_personnel');
        $list=$warehouse_personnel->field('id,uid,wid')->where($where)->find();
        if($list){
            $data['longitude']=$longitude;
            $data['latitude']=$latitude;
            $id=$warehouse_personnel->where($where)->save($data);
            if($id!=false){
                $wdldata['wp_uid']=$user_id;
                $wdldata['longitude']=$longitude;
                $wdldata['latitude']=$latitude;
                $wdldata['add_time']=gmtime();
                $welid=M('warehouse_diliveryman_log')->add($wdldata);
                if($welid){
                    returnApiSuccess(array('id'=>$welid),'定位收集成功');
                }else{
                    returnApiError('定位收集记录失败');
                }
            }else{
                returnApiError('定位收集失败');
            }
        }else{
            returnApiError('查无此人或者账号被禁用');
        }

    }

    /*TODO 插入到配送订单列表中*/
    public function deliver_order(){
        //$user_id=I('post.user_id','intval');
        $order_id=I('post.order_id','intval');
        $adminid=I('post.adminid','intval');
        if(!isset($order_id) || !isset($adminid)){
            returnApiError('参数错误');
        }
        //$where['user_id']=$user_id;
        $where['order_id']=$order_id;

        $where['pay_status']=array('EGT',2);
        $order=M('order_info')->field('order_id,order_sn,user_id,consignee,country,province,city,district,address,mobile,add_time,pay_time,order_status,shipping_status,pay_status,is_presell')->where($where)->find();

        if($order){
            $data=array(
                'order_id'=>$order['order_id'],
                'order_sn'=>$order['order_sn'],
                'user_id'=>$order['user_id'],
                'order_consignee_name'=>$order['consignee'],
                'country'=>$order['country'],
                'province'=>$order['province'],
                'city'=>$order['city'],
                'district'=>$order['district'],
                'order_consignee_addr'=>$order['address'],
                'order_consignee_phone'=>$order['mobile'],
                'add_time'=>gmtime(),
                'order_paytime'=>$order['pay_time'],
                'order_status'=>0
            );
            $order_goods=M('order_goods')->field('rec_id,order_id,goods_id')->where(array('order_id'=>$order['order_id']))->select();

//         	$good_ids='';
            $good_ids=array();
            if($order_goods){
//         		foreach ($order_goods as $k=>$v){
//         			$good_ids.=$v['goods_id'].',';
//         		}
//         		if($good_ids){
//         			$good_ids=substr($good_ids,0,strlen($good_ids)-1);
//         		}
                foreach ($order_goods as $k=>$v){
                    $good_ids[]=$v['goods_id'];
                }
                $good_ids = implode(',', $good_ids);
                $data['order_goods']=$good_ids;
                $id=M('warehouse_deliver_order')->add($data);
                if($id){
                    /*按配送区域自动分派仓库*/
                    //$this->auto_updateorder_warehouse($user_id, $order_id);
                    M('order_info')->where($where)->save(array('shipping_status'=>3));//修改配送状态为配货中
                    $a=array(
                        'order_id'=>$order['order_id'],
                        'user_id'=>$adminid,
                        'order_status'=>1,
                        'shipping_status'=>3,
                        'pay_status'=>$order['pay_status'],
                        'action_note'=>'配货中'
                    );
                    $this->record_diliveryman_log($a);//记录配送员操作日志
                    returnApiSuccess(array('id'=>$id),'配货订单成功');
                }else{
                    returnApiError('配货订单失败');
                }
            }else{
                returnApiError('空订单，没有任何商品');
            }

        }else{
            w_log('deliver_order_test',"'查无此订单");
            returnApiError('查无此订单');
        }
    }

    /*
     * TODO 按配送区域自动分派仓库
     * */
    public   function auto_updateorder_warehouse(){
        $user_id=I('post.user_id','intval');
        $order_id=I('post.order_id','intval');

        return D("Orderinfo")->auto_updateorder_warehouse($user_id,$order_id);
    }

    /*TODO 根据ID获取区域对应名称*/
    public  function get_region_name($id){
        $res=M('region')->where(array('region_id'=>$id))->find();
        return $res['region_name'];
    }
    /*
     * TODO 检查配送员是否合法,合法返回数组
     * */
    public function check_warehouse_personnel($uid,$position=2){
        $res=M('warehouse_personnel')->where(array('uid'=>$uid,'status'=>1))->find();
        if($res['uid']&&$res['position']==$position){
            return $res;
        }else{
            return false;
        }
    }

    /*
     * TODO 根据后台用户ID获取当前用户数据
     * */
    public function get_admin_user_name($uid){
        $res=M('admin_user')->where(array('user_id'=>$uid))->find();
        if($res){
            $warehouse_user = M('warehouse_personnel')->field('name,phone')->where(array('uid'=>$uid))->find();
            $res['phone'] = $warehouse_user['phone'];
            $res['name'] = $warehouse_user['name'];
//            $res['phone'] = M('warehouse_personnel')->where(array('uid'=>$uid))->getField('phone');
//            $res['name'] = M('warehouse_personnel')->where(array('uid'=>$uid))->getField('name');
            $res['user_account'] = $res['user_name'];
            if(!empty($res['name'])){
                $res['user_name'] = $res['name']." [ ".$res['user_name']." ]";
            }
//		   dump(M('warehouse_personnel')->getlastsql());
//		   dump($res);
            return $res;
        }else{
            return false;
        }
    }


    /**
     * 写入订单物流信息
     * @param $order_id
     * @param $shipping_status
     * @param $remark
     */
    public function record_logistics($order_id, $shipping_status, $remark){
        $data['log_time']=gmtime();
        $data['remark']=$remark;
        $data['shipping_status']=$shipping_status;
        $data['order_id']=$order_id;
        M('logistics')->add($data);
    }


    /*
     * TODO 记录配送员操作日志
     * */
    public function record_diliveryman_log($a=array(),$extend_data=array()){
        $data['order_id']=$a['order_id'];
        $user=$this->get_admin_user_name($a['user_id']);
        if(!$user){
            return false;
        }
        $wp=M('warehouse_personnel')->where(array('uid'=>$a['user_id'],'status'=>1))->find();;

        $data['con_phone'] = $wp['phone'];

        $juese='';
        if($wp){
            $data['longitude'] = $wp['longitude'];
            $data['latitude'] = $wp['latitude'];
            if($wp['position']==1){
                $juese='配货';
            }elseif ($wp['position']==2){
                $juese='配送';
            }elseif ($wp['position']==3){
                $juese='仓管';
            }
        }
        if(!empty($extend_data)){
            $data['action_user']=$extend_data['shipping_exman_name']."[.".$user['user_account']."]—角色：".$juese."   ".$extend_data['shipping_exman_mobile'];
        }else{
            if($wp['phone']){
                $data['action_user']=$user['user_name']." [ ".$wp['phone']." ] ".$juese;
            }else{
                $data['action_user']=$user['user_name']." ".$juese;
            }
        }

        $client_type = I("post.client_type");
        $version = I("post.version");
        if($client_type==1){
            $client_name = "Android";
        }elseif ($client_type==2){
            $client_name = "iOS";
        }else{
            $client_name = "未知";
        }

        $data['order_status']=$a['order_status'];
        $data['shipping_status']=$a['shipping_status'];
        $data['pay_status']=$a['pay_status'];
        $data['action_place']=0;
        $data['action_note']=$a['action_note']." By ".$client_name." [ ".$version." ]";
        $data['action_type'] = empty($a['action_type']) ? 0 : $a['action_type'] + 0;    //预警类型

        $data['log_time']=gmtime();
        $data['user_id']=$a['user_id'];
        $data['to_user']=$a['to_user'];
//        print_r($data);die;
        $res = M('order_action')->add($data);
        return $res;
    }


    /**
     * TODO 插入预警单
     * @param $order_sn
     * @param int $type
     * @return mixed
     */
    protected function alarm_log($order_sn, $type=6)
    {
        $data = array(
            'order_sn'      =>  $order_sn,
            'type'          =>  $type,
            'trigger_time'  =>  time(),
        );
        return M('alarm_log')->add($data);
    }

    /**
     * TODO 射线法计算坐标是否在规定图形内
     * @param $polygon
     * @param $longitude
     * @param $latitude
     * @return bool
     */
    private function isPointInPolygon($polygon, $longitude, $latitude){
        $count = count($polygon);
        $px = $longitude;
        $py = $latitude;
        $flag = false;
        for ($i = 0, $j = $count - 1; $i < $count; $j = $i, $i++) {
            $sy = $polygon[$i]['lng'];
            $sx = $polygon[$i]['lat'];
            $ty = $polygon[$j]['lng'];
            $tx = $polygon[$j]['lat'];
            if ($px == $sx && $py == $sy || $px == $tx && $py == $ty)
            {
                return true;
            }
            if ($sy < $py && $ty >= $py || $sy >= $py && $ty < $py) {
                $x = $sx + ($py - $sy) * ($tx - $sx) / ($ty - $sy);
                if ($x == $px){
                    return true;
                }
                if ($x > $px){
                    $flag = !$flag;
                }

            }
        }
        return $flag;
    }


    /**
     *更改订单的收获时间
     * TODO 延迟订单
     */
    public function change_distribution_time(){
        $order_id=I('post.order_id','intval');
        $distribution_time=I('post.distribution_time','');
        $user_id = I('post.user_id','intval');
        $is_shipping_app =  I('post.is_shipping_app','intval');
        $next_monday =  I('post.next_monday',0, 'int');
        $remark =  I('post.remark','');
        $return_goods =  I('post.is_return_goods',0);
        $remark =  str_replace(" ",'',$remark);
        $deploy_info = $this->get_admin_user_name($user_id);
        //判断用户类型1 配货员  2配送员
        $wprow=M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('position');
        //dump($wprow);
        if($wprow!=1&&$wprow!=2){
            returnApiError("账户错误");
        }
        if(empty($order_id)){
            returnApiError('订单ID/配送时间为空');
        }else{

            //$map = array("order_id"=>$order_id);

            $dis_company = array(741,743,746,712,713,689,686,685,682,681,678,555,529,522,469,423);
            $map['outgo_id']=array("not in",$dis_company);
            $map['k3cn_sn'] = array("EXP","IS NULL");
            $map['order_id'] = $order_id;
            $map['196_admin_id'] = 0;
            $map['order_status'] = array("neq",2);
            $map['shipping_status'] = array("neq",2);
            $map['pay_status'] = array("in",array(2,3));
            $order = M('order_info')->field('wdr_id,pay_status,order_id,wid,user_id,order_sn,mobile,consignee,best_time,best_time_start,order_status,shipping_status,is_presell')->where($map)->find();
            if(empty($order)){
                returnApiError("订单已确认收货/全部退款");
            }
            if($next_monday!=1){
                $shipping_arrive_time = explode('-', $distribution_time);
                $data['best_time_start'] = $shipping_arrive_time[0];
                $data['best_time'] = $shipping_arrive_time[1];

            }else{
                //
                $data['best_time_start'] = strtotime(date('Y-m-d',strtotime('+1 week last monday'))." ".date('H:i:s',$order['best_time_start']));
                $data['best_time'] = strtotime(date('Y-m-d',strtotime('+1 week last monday'))." ".date('H:i:s',$order['best_time']));
            }

            $dtime=time();
            $dftime=date('Y-m-d',$dtime);
            $order_best_time=date('Y-m-d',$data['best_time']);

            $huic_test = "";
            //dump($wprow);
            if($wprow==1){
                //dump("dd");
                //配货延迟，更改为未发货，并删除配货员ID
                if($return_goods==1) {
                    $data['shipping_status'] = 0;
                    $data['sorting_id'] = 0;
                    //dump($order_best_time);
                    //dump($dftime);
                }
                $action_note = $remark."//已延迟配货";
            }else if ($wprow==2){
                //配送员延迟 更改为 配货完成  并删除配送员ID
                if($order_best_time!=$dftime) {
                    $data['shipping_status'] = 5;
                    $data['station'] = 1;
                    $data['station_id'] = 0;
                    $data['station_time'] = 0;
                }
                $action_note = $remark."//已延迟配送";
            }else{
                returnApiError("用户角色ID不正常");
            }
            //exit();
            if($order_best_time!=$dftime) {
                $data['wp_userid'] = 0;
            }

            $diff_time = round(($data['best_time_start']-$order['best_time_start'])/3600/24);




            //修改期望送达时间
            $action_note .= " 由 [".date('Y-m-d H:i:s',$order['best_time_start'])."] - [".date('Y-m-d H:i:s',$order['best_time'])."]";

            $action_note .= " 延迟至 [".date('Y-m-d H:i:s',$data['best_time_start'])."] - [".date('Y-m-d H:i:s',$data['best_time'])."]";


            $change_order =  false;

            if(($order_best_time!=$dftime)&&$wprow==1){
                //配货员延迟到次日，改预售单
                $change_order =  true;
            }
            if(($wprow==2)&&($diff_time>1)){
                //配送员延迟两天以上，改预售单
                $data['shipping_status'] = 0;
                $data['wp_userid'] = 0;
//                $data['sorting_id'] = 0;
//                $data['sorting_time'] = 0;
                $change_order =  true;
                $data['outgo'] = 2;
                $data['station'] = 3;
                $data['station_id'] = 0;
                $data['station_time'] = 0;
                $huic_test = "<span style='color: #ff0000;'>订单需要回仓，请将商品拿回总仓</span>";
            }

            if($change_order){
                //处理订单现预售转变
                $this->change_order_pre_sale($order_id,$deploy_info);
            }
            $re = M('order_info')->where($map)->save($data);
            $getlastsql = M('order_info')->getlastsql();
            if($re){
                if(empty($data['shipping_status'])){
                    $data['shipping_status'] = M('order_info')->where($map)->getField("shipping_status");
                }
                $a = array (
                    'order_id' => $order_id,
                    'user_id' => $user_id,
                    'order_status' => OS_CONFIRMED,
                    'shipping_status' => $data['shipping_status'],
                    'pay_status' => PS_PAYED,
                    'to_user'=>1,
                    'action_note' => $action_note."</br>".$huic_test
                );
                $this->record_diliveryman_log ( $a ); // 记录配送员操作日志
                if($wprow==2){
                    //从配送群组中清除
                    if($is_shipping_app && $re!==false){
                        M('warehouse_deliver_order_group')->where($map)->delete();
                    }
                }elseif ($wprow==1){
                    //从配送群组中删除
                    $where['state']=0;
                    $where['user_id']=$user_id;
                    $count=M('sorting_order_group')->where($where)->select();
                    foreach ($count as $key=>$value){
                        $array_list = explode(",",$value['order_id']);
                        foreach ($array_list as $key_2=>$value_2){
                            if($value['order_id'] ==$value_2){
                                unset($array_list[$key_2]);
                                M("sorting_order_group")->where("id=".$value['id'])->setField('order_id',implode(",",$array_list));
                                break;
                            }
                        }
                    }
                }

                $datetime = date("Y-m-d",$data['best_time_start']);
                $smsremark['best_time'] = $datetime.' '.date("H:i:s",$data['best_time_start']).'-'.date("H:i:s",$data['best_time']);
                $smsremark['action'] = $remark;

                switch($_SERVER['SERVER_NAME']){
                    case 'api.xian3.com':
                        $thisurl='xian3.com';
                        break;
                    case 'api.test.shidexian.com':
                        $thisurl='test.shidexian.com';
                        break;
                    case 'api.shidexian.com':
                        $thisurl='w.shidexian.com';
                        break;
                    default:
                        $thisurl='w.shidexian.com';
                        break;
                }
                $code=md5($order['user_id'].'sdx@9999');
                $wechat_param=array();
                $wechat_param['url']='https://'.$thisurl.'/?index&sid='.$order['user_id'].'&code='.$code.'&lll=#!/reted?ordId='.$order['order_sn'];
                $wechat_param['keyword1']=$order['order_sn'];
                $wechat_param['keyword2']=$remark;
                $wechat_param['keyword3']="[".date('Y-m-d H:i:s',$order['best_time_start'])."] - [".date('Y-m-d H:i:s',$order['best_time'])."]";
                $wechat_param['keyword4']="[".date('Y-m-d H:i:s',$data['best_time_start'])."] - [".date('Y-m-d H:i:s',$data['best_time'])."]";

                //发送短信通知
                A("Smsapi")->send_message_api('delayed_order',$order['mobile'],$order['consignee'],0,$order['order_sn'],0,$order['user_id'],$smsremark,null,$wechat_param);

                //超时免单处理
                $distribution = new OrderDistributionTimeService();
                $distribution->delay_order_free_single($order_id, $order['wdr_id'], $data['best_time_start'], $data['best_time']);

                returnApiSuccess(null,'change success');
            }else{
                returnApiError('change fail:'.$getlastsql);
            }
        }
    }

    /**
     * TODO 问题订单提交
     */
    public function describe_order(){
        $user_id = I('post.user_id');
        $order_id = I('post.order_id');
        $content = I('post.content');
        $content =  str_replace(" ",'',$content);
        $is_shipping_app =  I('post.is_shipping_app','intval');
        $distribution_time=I('post.distribution_time','');
        if(empty($user_id)){
            returnApiError('参数错误');
        }
        if(empty($order_id)){
            returnApiError('参数错误');
        }
        if(empty($content)){
            returnApiError('参数错误');
        }

        //$this->check_user($user_id);

        $map['order_id'] = $order_id;
        $map['k3cn_sn'] = array("EXP","IS NULL");
        $order = M('order_info')->field('wdr_id,wp_userid,sorting_id,best_time_start,best_time,user_id,order_sn,mobile,consignee,order_sn,order_status,shipping_status')->where($map)->find();

        if($order['order_status']==OS_CONFIRMED && $order['shipping_status']==SS_UNSHIPPED){
            returnApiError('此订单已提交问题单处理，请勿重复操作');
        }


        $wprow=M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('position');

        if($wprow==1){
            //配货延迟，更改为未发货，并删除配货员ID
            $data['shipping_status'] = 0;
            $data['sorting_id'] = 0;
            $data['wp_userid'] = 0;
        }else if ($wprow==2){
            //配送员延迟 更改为 配货完成  并删除配送员ID
            $data['shipping_status'] = 5;
            $data['wp_userid'] = 0;
            $data['station'] = 1;
            //$data['outgo']=2;	    //商品需要回仓
            //$data['sorting_id'] = 0;
        }
        else{
            returnApiError("用户角色ID不正常");
        }

//        $mode_id = M("warehouse_deliver_region")->where(array("id"=>$order['wdr_id']))->getField("wdtype");

//        $distribution_time = M("distribution_time")->where(array("mode_id"=>$mode_id))->order("closing_time ASC")->find();

//		dump($distribution_time);
//		dump(M("distribution_time")->getLastSql());
//		exit();
        $shipping_arrive_time = explode('-', $distribution_time);
        $data['best_time_start'] = $shipping_arrive_time[0];
        $data['best_time'] = $shipping_arrive_time[1];

//        $data['best_time_start'] = strtotime(date("Y-m-d",strtotime("+1 day"))." ".$distribution_time['start_time'].":00");
//        $data['best_time'] = strtotime(date("Y-m-d",strtotime("+1 day"))." ".$distribution_time['end_time'].":00");


        $re = M('order_info')->where($map)->save($data);
        $order_data = M('order_info')->where($map)->find();

        $a = array (
            'order_id' => $order_id,
            'user_id' => $user_id,
            'order_status' => $order_data['order_status'],
            'shipping_status' => $order_data['shipping_status'],
            'pay_status' => $order_data['pay_status'],
            'action_note' => $content."//问题单提交 - 订单配送时间由".date("Y-m-d H:i:s",$order['best_time_start'])."-".date("Y-m-d H:i:s",$order['best_time'])." 延迟至".date("Y-m-d H:i:s",$data['best_time_start'])."-".date("Y-m-d H:i:s",$data['best_time']),
            'action_type'   =>  OA_WRONG,
            'to_user'=>1,
        );
        $this->record_diliveryman_log( $a ); // 记录配送员操作日志

        if($is_shipping_app && $re!==false){
            M('warehouse_deliver_order_group')->where($map)->delete();
        }
        $datetime = date("Y-m-d",$data['best_time_start']);
        $smsremark['best_time'] = $datetime.' '.date("H:i:s",$data['best_time_start']).'-'.date("H:i:s",$data['best_time']);
        $smsremark['action'] = " [ ".$content." ] ";
        //发送短信通知
        //$send_result = A("Smsapi")->send_message_api('describe_order_notice',$order['mobile'],$order['consignee'],0,$order['order_sn'],0,$order['user_id']);
        $send_result = A("Smsapi")->send_message_api('question_order',$order['mobile'],$order['consignee'],0,$order['order_sn'],0,$order['user_id'],$smsremark);
//        问题单
//        $this->alarm_log($order['order_sn']);

        if($re){
            returnApiSuccess(null,'change success');
        }else{
            returnApiError('change fail');
        }


    }

    /*TODO 创建配送群组*/
    public function group_create(){
        if(!IS_POST){
            returnApiError('error request');
        }
        $user_id=I('post.user_id','intval');
        $order_id_list  = I('post.order_id_list');
        $name = I('post.name');

        if(empty($user_id)){
            returnApiError('参数错误');
        }
        if(empty($order_id_list)){
            returnApiError('参数错误');
        }
        if(empty($name)){
            returnApiError('参数错误');
        }

        $this->check_user($user_id);

        $group_id = $this->create_order_group($user_id, $name);
        if($group_id){
            //将配送订单加入到群组
            $result = $this->add_to_group($group_id, $order_id_list,$user_id);

            $map = array('go.group_id'=>$group_id);
            $order_info = M('order_info');
            $order_list = $order_info->alias('o')->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')->field('o.user_id as user_id,o.order_id as order_id,o.order_sn as order_sn,o.mobile as mobile,o.consignee as consignee,o.best_time as best_time,o.best_time_start,go.take_no as take_no')->where($map)->select();


            $remark['phone'] = M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('phone');
            //发送短信
            foreach ($order_list as $order){

                $ver_code = getSmsCode();
                $sms_data['order_id'] = $order['order_id'];
                $sms_data['code'] = $ver_code;
                M("order_verif_code")->add($sms_data,$options=array(),$replace=true);
                $remark['code'] = $ver_code;

                //初始化时区，解决时区不正确的问题
                date_default_timezone_set('PRC');
                if($order['best_time_start']==0){
                    if($order['is_presell']==1){
                        $new_best_time = date("Y-m-d",$order['best_time'])." 20:30:00";
                        $order['best_time'] = strtotime($new_best_time)-1;
                        $order['best_time_start'] = strtotime(date("Y-m-d",$order['best_time'])." 10:00:00");
                    }else{
                        $order['best_time_start'] = $order['best_time']-2*3600;
                    }
                }
                $datetime = date("Y-m-d",$order['best_time_start']);

                $remark['best_time'] = $datetime.' '.date("H:i:s",$order['best_time_start']).'-'.date("H:i:s",$order['best_time']);

                $wechat_param=array();

                switch($_SERVER['SERVER_NAME']){
                    case 'api.xian3.com':
                        $thisurl='xian3.com';
                        break;
                    case 'api.test.shidexian.com':
                        $thisurl='test.shidexian.com';
                        break;
                    case 'api.shidexian.com':
                        $thisurl='w.shidexian.com';
                        break;
                    default:
                        $thisurl='w.shidexian.com';
                        break;
                }
                $oid=$order['user_id'];
                $Code=md5($oid.'sdx@9999');

                $goods_name=M("order_goods")->where(array('order_id'=>$order['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order['order_id'].')')))->limit(1)->getField("goods_name");
                $goods_number=M("order_goods")->where(array('order_id'=>$order['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order['order_id'].')')))->count();

                $name = M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('name');

                $wechat_param['url']="https://".$thisurl."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$order['order_id']."&utm_source=GZHshipping_start_notice";
                $wechat_param['first']='尊敬的'.$order['consignee'].'，您所订购的'.$goods_name.'等'.$goods_number.'件商品已经在配送中，预计到达时间为'.$remark['best_time'].'，请保持手机畅通。';
                $wechat_param['keyword1']=$order['order_sn'];
                $wechat_param['keyword2']=$name;
                $wechat_param['keyword3']=$remark['phone'];
                $wechat_param['remark']="您的订单收货码为：[ ".$ver_code." ],确认收货时请将此验证码提供给配送员";
                A("Smsapi")->send_message_api('receipt_verification',$order['mobile'],$order['consignee'],0,$order['order_sn'],0,$order['user_id'],$remark,'',$wechat_param);
            }
            $result['error_code'] = 100;
            returnApiSuccess($result,'创建群组成功');
        }else{
            returnApiError('创建群组失败，请重试');
        }
    }

    private function create_order_group($user_id,$group_name){
        $data = array();
        $data['user_id'] = $user_id;
        $data['name'] = $group_name;
        $data['create_time'] = gmtime();
        $group_id = D('warehouse_deliver_group')->add($data);

        if(!$group_id){
            returnApiError('创建群组失败，请重试');
        }
        return $group_id;
    }

    /**
     * todo 群组配送
     * @param $group_id
     * @param $order_id_list
     * @param $user_id
     * @return mixed
     */
    private function add_to_group($group_id, $order_id_list, $user_id){
        $group_order_list = array();
        $order_id_list = explode(',', $order_id_list);
        //过滤已经是配送中的order
        $order_info = D('order_info');
        //获取待配送的订单，order_status=>1,shipping_status->3
        $company_array = M("distribution_company_user")->where(array("user_id"=>$user_id))->getField("company_id",true);
        if(!empty($company_array)){
            $no_delier_orderid_list = $order_info->
            where(array('order_id'=>array('in',$order_id_list),'order_status'=>array('neq','2'),'station'=>1,'shipping_status'=>5,'pay_status'=>array('EGT',PS_PAYED),'distribution_company_id'=>array('in',$company_array)))
                ->getField('order_id',true);
        }else{
            $no_delier_orderid_list = $order_info->
            where(array('order_id'=>array('in',$order_id_list),'order_status'=>array('neq','2'),'station'=>1,'shipping_status'=>5,'pay_status'=>array('EGT',PS_PAYED)))
                ->getField('order_id',true);
        }

        //将待配送的订单加入到群组中，并修改状态为配送中

        //获取当前群组订单格式，take_no在此基础上增加
        $deliver_order_group =  D('warehouse_deliver_order_group');
        $count = $deliver_order_group->where(array('group_id'=>$group_id))->count();
        if($count>0){
            $take_no = $count +1;
        }else{
            $take_no = 1;
        }
        foreach ($no_delier_orderid_list as $order_id){
            $order_data = array();
            $order_data['group_id'] = $group_id;
            $order_data['order_id'] = $order_id;
            $order_data['take_no'] = $take_no;
            $group_order_list[] = $order_data;
            $take_no++;
        }
        if(count($group_order_list)>0){
            $res = $deliver_order_group->addAll($group_order_list);
            if($res){
                //修改配送订单状态为配送中
                $where = array('order_id'=>array('in',$no_delier_orderid_list));
                D('warehouse_deliver_order')->where($where)->setField('order_status',1);
                //修改订单状态为已发货
                $savedata = array();
                $savedata['order_status']=OS_SPLITED;
                $savedata['shipping_status']=SS_SHIPPED;
                $savedata['station']=2; //开始配送，修改到站状态为 已出站
                $data['shipping_time']=gmtime();
                D('order_info')->where($where)->save($savedata);
//     			$order_list = M('order_info')->where(array('order_id'=>array('in',$order_id_list)))->select();

                foreach ($no_delier_orderid_list as $order_id){
                    //记录配送员操作日志
                    $act=array(
                        'order_id'=>$order_id,
                        'user_id'=>$user_id,
                        'order_status'=>OS_SPLITED,
                        'shipping_status'=>SS_SHIPPED,
                        'pay_status'=>PS_PAYED,
                        'action_note'=>'群组。已发货'
                    );
                    $this->record_diliveryman_log($act);
                    $this->record_logistics($order_id,1,"开始配送");
                }
                $result['error_code']=100;
                return $result;
            }else{
                returnApiError('配送订单加入群组失败');
            }
        }else{
            returnApiError('没有待配送订单');
        }
    }

    /**
     *TODO 群组列表
     */
    public function group_list(){
        if(!IS_POST){
            returnApiError('error request');
        }
        $user_id=I('post.user_id','intval');
        $page  = I('post.page','intval');

        if(empty($user_id)){
            returnApiError('参数错误');
        }
        if(empty($page)){
            returnApiError('参数错误');
        }

        $this->check_user($user_id);

        $map = array('user_id'=>$user_id,'status'=>1);
        $deliver_group = M('warehouse_deliver_group');
        $count = $deliver_group->where($map)->count();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }

        $list = $deliver_group->where($map)->limit($pagearr['firstpage'],$pagearr['pagesize'])->order('create_time asc')->select();
        if($list){
            foreach ($list as $key=>$group){
                $count =M('warehouse_deliver_order_group')->where(array('group_id'=>$group['group_id']))->count();
                $list[$key]['count'] = $count;
            }
            $result = array('list'=>$list,'is_last'=>$is_last);
            returnApiSuccess($result);
        }else{
            returnApiError('没有数据');
        }
    }

    public function group_sub_list(){
        if(!IS_POST){
            returnApiError('error request');
        }

        $user_id=I('post.user_id','intval');
        $group_id = I('post.group_id','intval');
        $page  = I('post.page','intval');

        if(empty($user_id)){
            returnApiError('参数错误');
        }
        if(empty($group_id)){
            returnApiError('参数错误');
        }
        if(empty($page)){
            returnApiError('参数错误');
        }

        $this->check_user($user_id);

        $id = D('warehouse_deliver_group')->where(array('group_id'=>$group_id,'user_id'=>$user_id))->getField('group_id');
        if(empty($id)){
            returnApiError('此群组不存在或不是该用户创建的');
        }
        $map = array('go.group_id'=>$group_id);
        $deliver_order = M('order_info');

        $count = $deliver_order->alias('o')->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')->where($map)->count();
        $pagearr=show_page($count, $page);
        if($page>=$pagearr['pagecount']){
            $is_last=1;
        }else{
            $is_last=0;
        }

        if($count){
            $field = 'o.order_id,o.order_sn as order_num,o.order_status as order_status,o.shipping_status as shipping_status,o.add_time as order_time,o.consignee as name,o.mobile as phone,o.country as country,o.province as province,o.city as city,o.district as district,o.address as address,o.sign_building as sign_building,o.address_name as address_name,go.take_no as take_no';
            $list = $deliver_order->alias('o')->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')->field($field)->where($map)->order('go.take_no asc')->limit($pagearr['firstpage'],$pagearr['pagesize'])->select();
            if(!empty($list)){
                $order_goods = M('order_goods');
                foreach ($list as $key=>$data){
                    $country_name=$this->get_region_name($data['country']);
                    $province_name=$this->get_region_name($data['province']);
                    $city_name=$this->get_region_name($data['city']);
                    $district_name=$this->get_region_name($data['district']);
                    $list[$key]['address']=$country_name.$province_name.$city_name.$district_name.$data['address'].$data['sign_building'].$data['address_name'];
                    $list[$key]['order_time']=date('Y-m-d H:i:s',$data['order_time']+(8*3600));

                    if($data['order_status'] == OS_SPLITED && $data['shipping_status'] == SS_RECEIVED){
                        $list[$key]['order_state']=2;
                    }else{
                        $list[$key]['order_state']=1;
                    }

                    $goods=$order_goods->field('goods_sn as goods_number,goods_id as id,goods_name as name,goods_price as price,goods_number as `count`')->where(array('order_id'=>$data['order_id']))->select();
                    $list[$key]['goods_list'] = $goods;
                }
                $result = array('list'=>$list,'is_last'=>$is_last);
                returnApiSuccess($result);
            }else{
                returnApiError('没有数据');
            }
        }else{
            returnApiError('没有数据');
        }
    }

    /**
     * TODO 群组完成
     */
    public function group_distributed(){
        if(!IS_POST){
            returnApiError('error request');
        }

        $user_id=I('post.user_id','intval');
        $group_id = I('post.group_id','intval');

        if(empty($user_id)){
            returnApiError('参数错误');
        }
        if(empty($group_id)){
            returnApiError('参数错误');
        }

        $this->check_user($user_id);

        $id = D('warehouse_deliver_group')->where(array('group_id'=>$group_id,'user_id'=>$user_id))->getField('group_id');
        if(empty($id)){
            returnApiError('此群组不是该用户创建的');
        }
        $map = array('go.group_id'=>$group_id);
//    	$deliver_order = M('warehouse_deliver_order');
//    	$order_list = $deliver_order->alias('o')
//    	              ->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')
//    	              ->join('inner join '.C('DB_PREFIX').'order_info oi on oi.order_id = o.order_id')
//    	              ->field('DISTINCT( o.order_id) as order_id,o.user_id as user_id,o.order_consignee_phone as mobile,o.order_consignee_name as consignee,o.order_sn as order_sn,oi.wid,oi.order_status as order_status,oi.shipping_status as shipping_status,oi.pay_status as pay_status')
//    	              ->where($map)
//    	              ->select();
        $deliver_order = M('order_info');
        $order_list = $deliver_order->alias('o')
            ->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')
            ->field('DISTINCT( o.order_id) as order_id,o.user_id as user_id,o.mobile,o.consignee,o.order_sn,o.wid,o.order_status,o.shipping_status,o.pay_status,o.order_amount,o.money_paid,o.surplus')
            ->where($map)
            ->select();
        if(!empty($order_list)){
            $order_ids = array();
            foreach ($order_list as $key=>$order){
                if($order['order_status']==5 && $order['shipping_status']==2){
                    unset($order_list[$key]);
                    continue;
                }
                $order_ids[]= $order['order_id'];
                /* 收货确认减冻结库存*/
                $is_shipping_status = M("order_action")->where(array("order_id"=>$order['order_id'],"shipping_status"=>2))->count();
                if(empty($is_shipping_status)){
                    $this->order_buckle_inventory($order);
                }
                //$this->order_buckle_inventory($order);
            }

            if(count($order_ids)>0){
                $where = array('order_id'=>array('in',$order_ids));

                //修改订单状态为已发货
                $savedata = array();
                $savedata['order_status']=OS_SPLITED;
                $savedata['shipping_status']=SS_RECEIVED;
                $savedata['confirm_time']=gmtime();
                $savedata['wp_userid']=$user_id;
                D('order_info')->where($where)->save($savedata);

                //修改配送订单状态为已配送
                D('warehouse_deliver_order')->where($where)->setField('order_status',2);
                foreach ($order_ids as $o_id){
                    $a = array (
                        'order_id' => $o_id,
                        'user_id' => $user_id,
                        'order_status' => OS_SPLITED,
                        'shipping_status' => SS_RECEIVED,
                        'pay_status' => PS_PAYED,
                        'action_note' => '配送完成,收货确认'
                    );
                    $this->record_diliveryman_log ( $a ); // 记录配送员操作日志
                    $this->record_logistics($o_id,2,"收货确认");

                    //订单超时处理
                    $distribution = new OrderDistributionTimeService();
                    $distribution->add_order_info_overtime($o_id, 3);
                }



                foreach ($order_list as $key=>$v){

                    $wechat_param=array();

                    switch($_SERVER['SERVER_NAME']){
                        case 'api.xian3.com':
                            $thisurl='xian3.com';
                            break;
                        case 'api.test.shidexian.com':
                            $thisurl='test.shidexian.com';
                            break;
                        case 'api.shidexian.com':
                            $thisurl='w.shidexian.com';
                            break;
                        default:
                            $thisurl='w.shidexian.com';
                            break;
                    }
                    $oid=$v['user_id'];
                    $Code=md5($oid.'sdx@9999');

                    $goods_name=M("order_goods")->where(array('order_id'=>$v['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$v['order_id'].')')))->limit(1)->getField("goods_name");
                    $goods_number=M("order_goods")->where(array('order_id'=>$v['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$v['order_id'].')')))->count();

                    $louxiaoer_info=A("Smsapi")->get_louxiaoer_info($v['order_id']);

                    $housekeeper='';
                    if(!empty($louxiaoer_info['name']) && !empty($louxiaoer_info['phone'])){
                        $housekeeper="";
                    }else{
                        $housekeeper="";
                    }

                    $wechat_param['url']="https://".$thisurl."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$v['order_id']."&utm_source=GZHorder_finish";
                    $wechat_param['first']='尊敬的'.$v['consignee'].',您所订购的'.$goods_name.'等'.$goods_number.'件商品已经成功送达';
                    $wechat_param['keyword1']=$v['order_sn'];
                    $wechat_param['keyword2']=sprintf("%.2f",($v['order_amount']+$v['money_paid']+$v['surplus']));
                    $wechat_param['keyword3']=date("Y-m-d H:i:s");
                    $wechat_param['remark']=$housekeeper;

                    //发送订单配送完成短信给收货人
                    $send_result = A("Smsapi")->send_message_api('order_finish',$v['mobile'],$v['consignee'],0,$v['order_sn'],0,$v['user_id'],array(),'',$wechat_param);

                    //确认收货，赠送红包
                    D('Userbonus')->send_bonus_to_user($v['user_id'],$v['order_id']);

                }
            }
        }

        $map = array('group_id'=>$group_id);
        //修改群组状态
        $deliver_group = D('warehouse_deliver_group');
        $savedata['end_state'] = 1;
        $savedata['status'] = 0;
        $res = $deliver_group->where($map)->save($savedata);

        returnApiSuccess ( '', '收货确认成功' );
    }

    /**
     * TODO 工作中心
     */
    public function work_info(){
        $user_id=I('post.user_id','intval');

        if(empty($user_id)){
            returnApiError('参数错误');
        }

        $this->check_user($user_id);

        $userinfo = M('warehouse_personnel')->field('uid,phone,wid')->where(array('uid'=>$user_id))->find();
        $phone = $userinfo['phone'];
        //获取当天日期
        $curdate = date("Y-m-d");
        //获取当月日期
        $curmonth = date("Y-m");
        //日订单量
        $day_order_count = $this->get_day_order_count($curdate, $user_id);
        //日平均分单量
        $day_order_count_avg = $this->get_day_order_count_avg($curdate,$userinfo['wid']);
        //月订单量
        $month_order_count = $this->get_month_order_count($curmonth,$user_id);
        //扫单准点率
        $scan_accurate = $this->get_scan_accurate($curmonth,$user_id);
        //送达准点率
        $arrived_accurate = $this->get_arrived_accurate($curmonth,$user_id);

        $result = array();

        $result['user_id'] = $user_id;
        $result['phone'] = $phone;
        $result['day_order_count'] = $day_order_count;
        $result['day_order_count_avg'] = $day_order_count_avg;
        $result['month_order_count'] = $month_order_count;
        $result['scan_accurate'] = $scan_accurate;
        $result['arrived_accurate'] = $arrived_accurate;

        returnApiSuccess ($result);
    }

    /*
     * TODO 日订单量，显示该配送员当日的配送订单量
     */
    private function get_day_order_count($date,$uid=0){
        $begintime = strtotime($date);
        $endtime = strtotime($date." 23:59:59");
        if($uid){
            $map['wp_userid'] = $uid;
        }
        $map['confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
        //$map['order_status']=OS_SPLITED;
        $map['shipping_status']=SS_RECEIVED;
        $count = M('order_info')->where($map)->count();

        return $count;
    }

    /*
     * TODO 日平均分单量，显示当日该门店的配送员平均分单量，每小时更新
     */
    private function get_day_order_count_avg($curdate,$wid=0){
        $begintime = strtotime($curdate);
        $endtime = strtotime($curdate." 23:59:59");

        $map = array();
        $map['o.confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
        //$map['o.order_status']=OS_SPLITED;
        $map['o.shipping_status']=SS_RECEIVED;

        $user_map = array();
        $user_map['status'] = 1;
        if($wid){
            $map['p.wid'] = $wid;
            $user_map['wid']=$wid;
        }
        $order_info = M('order_info');
        $count = $order_info->alias('o')->field('distinct(order_id)')->join("left join ".C('DB_PREFIX')."warehouse_personnel p on o.wp_userid = p.uid")->where($map)->count();
        $user_count = M('warehouse_personnel')->where($user_map)->count();
        $count_avg = round($count/$user_count,2);
        return $count_avg;
    }

    /*
     * TODO 月订单量，显示该配送员个人该月订单量。点击可进入“历史订单”
     * user_id为0则为月总订单量
     */

    private function get_month_order_count($curmonth,$user_id=0){
        $begintime = strtotime($curmonth.'-01 00:00:00')-28800;
        $lastday = date('Y-m-d', strtotime("$curmonth +1 month -1 day"));
        $endtime = strtotime($lastday." 23:59:59")-28800;

        if($user_id){
            $map['wp_userid'] = $user_id;
        }
        $map['confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
        //$map['order_status']= array('neq',2);
        $map['shipping_status']= 2;
        //$map['pay_status'] = array("in","2,3");
        $count = M('order_info')->where($map)->count();
        return $count;
    }
    /*
     * 扫单准点率：扫单率=（准扫单量/订单总量）*100%，漏单量=扫单发货时间超过用户期望最早时间点。
     */
    private function get_scan_accurate($curmonth,$user_id){
        $sum_count = $this->get_month_order_count($curmonth,$user_id);
        $punctual_count = $this->get_punctual_order_count($curmonth, $user_id);

        $rate = round($punctual_count/$sum_count*100,2)."%";
        return $rate;
    }

    /*
     * 准扫单量
     */
    private function get_punctual_order_count($curmonth,$user_id){
        $begintime = strtotime($curmonth.'-1');
        $days = date('t',strtotime($curmonth));
        $endtime = strtotime($curmonth.'-'.$days." 23:59:59");

        if($user_id){
            $map['wp_userid'] = $user_id;
        }
        $map['confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
        $map['_string'] = "shipping_time<=(best_time-2*3600)";
        $map['order_status']=OS_SPLITED;
        $map['shipping_status']=SS_RECEIVED;
        $count = M('order_info')->where($map)->count();

        return $count;
    }

    /*
     * 送达准点率，（准点送达订单量/订单总量）*100%，未准点送达=没有在用户期望时间段内确认收货的订单。
     */
    private function get_arrived_accurate($curmonth,$user_id){
        $sum_count = $this->get_month_order_count($curmonth,$user_id);
        $arrived_count = $this->get_arrived_count($curmonth,$user_id);
        $rate = round($arrived_count/$sum_count*100,2)."%";
        return $rate;
    }

    /*
     * 准点送达订单量
     */
    private function get_arrived_count($curmonth,$user_id){
        $begintime = strtotime($curmonth.'-1');
        $days = date('t',strtotime($curmonth));
        $endtime = strtotime($curmonth.'-'.$days." 23:59:59");

        if($user_id){
            $map['wp_userid'] = $user_id;
        }
        $map['confirm_time'] = array(array('EGT',$begintime),array('ELT',$endtime)) ;
        $map['order_status']=OS_SPLITED;
        $map['shipping_status']=SS_RECEIVED;
        $map['_string'] = "confirm_time<=best_time";
        $count = M('order_info')->where($map)->count();

        return $count;
    }

    /**
     * TODO 群组发送信息
     */
    public function group_send_msg(){
        if(!IS_POST){
            returnApiError('error request');
        }
        $user_id=I('post.user_id','intval');
        $group_id = I('post.group_id','intval');
        $meet_time = I('post.meet_time','intval');
        $meet_address = I('post.meet_address');

        if(empty($user_id)){
            returnApiError('参数错误');
        }
        if(empty($group_id)){
            returnApiError('参数错误');
        }

        if(empty($meet_time)){
            returnApiError('meet_time参数错误');
        }
        if(empty($meet_address)){
            returnApiError('meet_address参数错误');
        }


        $this->check_user($user_id);

        $map = array('go.group_id'=>$group_id);
        $order_info = M('order_info');
        $order_list = $order_info->alias('o')->join('inner join '.C('DB_PREFIX').'warehouse_deliver_order_group go on go.order_id = o.order_id')->field('o.user_id as user_id,o.order_id as order_id,o.order_sn as order_sn,o.mobile as mobile,o.consignee as consignee,go.take_no as take_no')->where($map)->select();

        //发送短信
        $remark = array('');
        $remark['meet_time']= $meet_time;
        $remark['meet_address'] = $meet_address;
        $remark['phone'] = M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('phone');

        foreach ($order_list as $order){
            $remark['take_no'] = $order['take_no'];
            $send_result = A("Smsapi")->send_message_api('shipping_pickup_notice',$order['mobile'],$order['consignee'],0,$order['order_sn'],0,$order['user_id'],$remark);
        }

        $where = array('group_id'=>$group_id);
        //修改群组状态
        $deliver_group = D('warehouse_deliver_group');
        $deliver_group->where($where)->setField('send_state',1);

        $deliver_group_info = $deliver_group->where($where)->find();

        //如果配送完成修改群组状态
        if($deliver_group_info['end_state']==1){
            $deliver_group->where($where)->setField('status',0);
        }

        $result['error_code']=100;
        returnApiSuccess($result,'发送短信完成');

    }

    /**
     * TODO 获取配送时间
     */
    public function get_distribution_time(){
        $order_id =I("post.order_id",'intval');
        $get_fac = D('Useraddress')->check_serve_by_order_id($order_id);
        $mode_id = $get_fac['mode_id'];
        //查询送货时间
        $Distribution_time = D("Users")->distributie_time_list_new($mode_id);
        returnApiSuccess($Distribution_time,'Distribution_time');
    }

    /**
     *
     *
     *
     * TODO 修改密码
     */
    public function edit_password(){
        $name=I('post.name','');
        $password_old = I('post.password_old','');
        $password_new = I('post.password_new','');

        //判断密码强度
        if (!preg_match("/^[a-za-z]{1}([a-za-z0-9]|[._]){5,16}$/",$password_new)){
            returnApiError("密码不符合规则\n密码需要首字母/6-16位/无特殊字符");
        }




        $admin_user=M('admin_user');
        $ec_salt=$admin_user->field('ec_salt')->where(array('user_name'=>$name))->find();
        if(!empty($ec_salt['ec_salt'])){
            $password=md5(md5($password_old).$ec_salt['ec_salt']);
            $new_password = md5(md5($password_new).$ec_salt['ec_salt']);
        }else{
            $password=md5($password_old);
            $new_password = md5($password_new);
        }

        $row=$admin_user->field('user_id,user_name')->where(array('user_name'=>$name,'password'=>$password))->find();
        //dump($admin_user->getlastsql());
        if($row){
            $edit = $admin_user->where(array('user_name'=>$name,'password'=>$password))->setField('password',$new_password);
            if($edit){
                $data=array(
                    'log_time'=>gmtime(),
                    'user_id'=>$row['user_id'],
                    'log_info'=>$row['user_name']." [ ".$row['user_id']." ] 已成功修改密码",
                    'ip_address'=>get_client_ip()
                );
                M('admin_log')->add($data);
                returnApiSuccess(null,"修改成功");
            }else{
                returnApiError("内部错误：修改密码失败");
            }
        }else{
            returnApiError("原密码/用户名不匹配");
        }
    }

    /**
     * TODO 退单处理
     */
    public function return_order(){
        $user_id=I('post.user_id','intval');
        $order_id=I('post.order_id','intval');
        $remark=I('post.remark','');
        if(empty($remark)||is_numeric($remark)){
            returnApiError("请务必填写您退单的原因");
        }
        //$this->check_user($user_id);

        $where_tow['shipping_id'] = 3;
        $where_tow['pay_status'] = array('IN','2,3');
        $where_tow['order_status'] = array('NEQ',2);
        $where['order_id'] = $order_id;
        $where['shipping_status'] = array("in","0,1,3");	//配货中，配送中

        $order_info = M("order_info")->where($where)->find();
        if($order_info){
            if($order_info['shipping_status'] == 1){
                //配送中【退单操作】
                $a=array(
                    'order_id'=>$order_info['order_id'],
                    'user_id'=>$user_id,
                    'order_status'=>$order_info['order_status'],
                    'shipping_status'=>5,	//配货完成
                    'pay_status'=>$order_info['pay_status'],
                    'to_user'=>1,
                    'action_note'=>$remark.'///由发货中退回到配送完成'
                );
                $this->record_diliveryman_log($a);//记录配送员操作日志
                $data['wp_userid']=0;
                $data['shipping_status']=5;
                $data['station']=1; //改为已到站
                $r = M('order_info')->where("order_id = ".$order_info['order_id'])->save($data);
                if($r){
                    returnApiSuccess(null,"成功");
                }else{
                    returnApiError("失败");
                }
            }else{
                //配货中【退单操作】
                if($order_info['sorting_id'] >0){
                    $a=array(
                        'order_id'=>$order_info['order_id'],
                        'user_id'=>$user_id,
                        'order_status'=>$order_info['order_status'],
                        'shipping_status'=>0,	//未配货
                        'pay_status'=>$order_info['pay_status'],
                        'to_user'=>1,
                        'action_note'=>$remark.'///由配货中退回到未配货状态'
                    );
                    $this->record_diliveryman_log($a);//记录配送员操作日志
                    $data['sorting_id']=0;
                    $data['shipping_status']=0;
                    $r = M('order_info')->where("order_id = ".$order_info['order_id'])->save($data);
                    if($r){
                        returnApiSuccess(null,"成功");
                    }else{
                        returnApiError("失败");
                    }
                }
            }
        }else{
            returnApiError("无法进行此操作");
        }
    }
    /**
     * todo 新版获取配送时间
     */
    public function get_distribution_time_02(){
        $user_id = I("post.user_id");
        $order_id = I("post.order_id");
        $year = I("post.year");
        $month = I("post.month");
        $day = I("post.day");

        $a_ux = strtotime($year."-".$month."-".$day);
        if(time()-$a_ux>86400){
            returnApiError("没有时光机，不能选择过去的时间");
        }
        $a_date = date('Y-m-d',$a_ux);

        $b_date = date('Y-m-d');


        $wdr_id = M("order_info")->where(array("order_id"=>$order_id))->getField("wdr_id");
        $mode = M("warehouse_deliver_region")->where(array("id"=>$wdr_id))->getField("wdtype");
        //dump($get_fac);


        if(empty($mode)){
            returnApiError("无此配送区域");
        }

        $distribution_time_array = array();

        $distribution_time =  M("distribution_time")->field("start_time,end_time,closing_time,id")
            ->where(array("mode_id"=>$mode))->order("start_time asc")->select();

        if(empty($distribution_time)){
            //未找到此配送区域，返回为空
            returnApiError("区域错误");
        }


        $distribution_mode =  M("distribution_mode")->where(array("id"=>$mode))->getField("arrival_type");

        //今日配送时间
        if($distribution_mode==1){
            //次日达区域，只显示今天配送去为空
            $distribution_time_array_today =array();
        }else{
            //今日达区域，显示今天和明天
            foreach ($distribution_time as $value){
                $closing_time = str_replace(":","",$value['end_time']);
                $now_hour = date('H',time()).date('i',time());
                if($closing_time>$now_hour){
                    $distribution_time_array_today[] = array(
                        "value" =>strtotime(date("Y-m-d",time())." ".$value['start_time'].":00")."-".strtotime(date("Y-m-d",time())." ".$value['end_time'].":00"),
                        "title" =>"今日 {$value['start_time']} - {$value['end_time']}",
                        'closing'	=>	"今日 {$value['closing_time']}",
                        "is_free_single" => $this->get_wdr_order_free_single($wdr_id,$value['id'])
                    );
                }
            }
            if(empty($distribution_time_array_today)){
                $distribution_time_array_today =array();
            }
        }
        //明天配送时间
        foreach ($distribution_time as $value){
            $distribution_time_array_tomorrow[] = array(
                "value" =>strtotime($year."-".$month."-".$day." ".$value['start_time'].":00")."-".strtotime($year."-".$month."-".$day." ".$value['end_time'].":00"),
                "title" =>"{$year}-{$month}-{$day} {$value['start_time']} - {$value['end_time']}",
                'closing'	=>	"{$value['closing_time']}",
                "is_free_single" => $this->get_wdr_order_free_single($wdr_id,$value['id'])
            );
        }
        if($a_date==$b_date){
            //提交今天的时间
            $data['list'] = array_values($distribution_time_array_today);
        }else{
            //提交明天的时间
            $data['list'] = array_values($distribution_time_array_tomorrow);
        }
        returnApiSuccess($data,"今日配送时间");

    }

    /**
     * 获取区域订单峰值
     * Created By caicm
     * @param $wdr_id
     * @param $time_id
     * @return mixed
     */
    public function get_wdr_order_free_single($wdr_id, $time_id)
    {
        $where = array(
            'wdr_id' => $wdr_id,
            'time_id' => $time_id
        );
        //$field = 'order_peak,is_free_single';
        $is_free_single = M('warehouse_deliver_region_order_peak')->where($where)->getField("is_free_single");
        if(empty($is_free_single)){
            return 0;
        }else{
            return $is_free_single;
        }


    }
    /**
     * todo 修改订单状态【预售现售转换】
     * @param $order_id    订单ID
     * @param $deploy_info 操作者信息
     */
    public function change_order_pre_sale($order_id,$deploy_info){
        //将处理现售商品
        $goods_list =M("order_goods")->where(array("order_id"=>$order_id))->select();
        if(count($goods_list)>0){
            $rdgoods=array();
            //处理退货退款的商品
            $rdsql='select goods_id,SUM(refund_number) as refund_number from sdx_refund_detail where order_id='.$order_id.' group by goods_id';
            $rdlist=M()->query($rdsql);
            if($rdlist){
                foreach ($rdlist as $key=>$val){
                    $rdgoods[$val['goods_id']]=$val['refund_number'];
                }
            }

            foreach ($goods_list as $k=>$v){
                $goods_morrow=M("goods")->where(array("goods_id"=>$v['goods_id']))->getField('is_auto_morrow_presell');
                if($v['is_presell']==0 && $goods_morrow){  //有启用“次日达自动预售”的现售商品
                    $goodsstorage = M("goods_storage")->field("id,wid,goods_id,goods_sn,goods_name,practical_num,freeze_num,inferior_quality_num")->where(array("wid"=>$order['wid'],"goods_id"=>$v['goods_id']))->find();
                    //获取实际库存缓存
                    $cache_goods_practical_num = get_goods_practical_num_cache($v['goods_id'],$goodsstorage['wid'],$goodsstorage['practical_num']);
                    //获取队列库存缓存
                    $cache_queue_goods_stock = get_queue_goods_stock($v['goods_id'],$goodsstorage['wid']);
                    if ($goodsstorage) {
                        M("order_goods")->where(array("rec_id"=>$v['rec_id']))->setField("is_presell",1);
                        if(!empty($rdgoods[$v['goods_id']])){
                            $refund_number=$rdgoods[$v['goods_id']];
                            $v['goods_number']=$v['goods_number']-$refund_number;
                        }
                        $practical_num = $goodsstorage['practical_num'] + $v['goods_number'];
                        $freeze_num = $goodsstorage['freeze_num'] - $v['goods_number'];
                        /* 商品实际库存+ 商品冻结库存- */
                        $goods_storage_sql = "UPDATE sdx_goods_storage
                                    SET practical_num = " . $practical_num . ",freeze_num=" . $freeze_num .
                            " WHERE wid = " . $goodsstorage['wid'] . " and goods_id=" . $v['goods_id'];

                        $flag = M()->execute($goods_storage_sql);

                        //更新实际库存缓存
                        if($flag!==false){
                            set_goods_practical_num_cache($v['goods_id'],$goodsstorage['wid'],$cache_goods_practical_num+$v['goods_number']);
                            set_queue_goods_stock($v['goods_id'],$goodsstorage['wid'],$cache_queue_goods_stock+$v['goods_number']);
                        }

                        /* 生成商品实际出入库记录 */
                        $goods_storage_record_sql = "INSERT INTO sdx_goods_storage_record
									(goods_storage_id,wpid,wid,goods_id,goods_sn, " .
                            "operation_num, real_num, frozen_num, defective_num, " .
                            "operation_userid, average_userid, operation_addtime, source_no,record_type,remark) VALUES (" .
                            $goodsstorage['id'] . ",0," . $goodsstorage['wid'] . "," . $goodsstorage['goods_id'] . ",'" . $goodsstorage['goods_sn'] . "'," .
                            $v['goods_number'] . "," . $practical_num . ",0,0,0," . $order['user_id'] . "," . gmtime() . ",'" . $order['order_sn'] . "',17,'在仓回流')";
                        M()->execute($goods_storage_record_sql);
                        /* 生成商品冻结出入库记录 */
                        $freeze_sql = "INSERT INTO sdx_goods_freeze_record
									(goods_storage_id,wid,goods_id,goods_sn,goods_name," .
                            "freeze_num, real_num, frozen_num, defective_num, " .
                            "operation_userid, average_userid, operation_addtime, source_no,record_type,remark) VALUES (" .
                            $goodsstorage['id'] . "," . $goodsstorage['wid'] . "," . $goodsstorage['goods_id'] . ",'" . $goodsstorage['goods_sn'] . "','" .
                            $goodsstorage['goods_name'] . "'," . $v['goods_number'] . ",0," . $freeze_num . ',0,0,' . $order['user_id'] . "," . gmtime() . ",'" . $order['order_sn'] . "',14,'在仓回流')";
                        M()->execute($freeze_sql);
                        $new_order_xx['shipping_status']=SS_UNSHIPPED;//修改订单配送状态为未发货
                        $new_order_xx['is_presell']=1;

                        M("order_info")->where(array("order_id"=>$order_id))->save($new_order_xx);
                        //
                        $note='该商品有启用“次日达自动预售”的现售<br />商品货号:('.$v['goods_sn'].'-ID:'.$v['goods_id'].')进行现售变预售';
                        $new_data['order_id'] = $order['order_id'];
                        $new_data['order_status'] = $order['order_status'];
                        $new_data['shipping_status'] = SS_UNSHIPPED;
                        $new_data['pay_status'] = $order['pay_status'];
                        $new_data['action_note'] = $note;
                        $new_data['action_user'] = $deploy_info['user_name']." [ ".$deploy_info['phone']." ] ";
                        $new_data['log_time'] = gmtime();
                        M("order_action")->add($new_data);
                    }else{
                        continue;
                    }
                }
            }
        }
    }

    /**
     * todo 操作订单回仓
     */
    public function order_back(){
        $user_id = I("post.user_id");
        $order_id = I("post.order_id");

        //$deploy_info = $this->get_admin_user_name($user_id);

        if(empty($order_id)){
            returnApiError('订单ID为空');
        }else{
            //配送员延迟两天以上，改预售单
            $data['shipping_status'] = 0;
            $data['wp_userid'] = 0;
//            $data['sorting_id'] = 0;
//            $data['sorting_time'] = 0;
            $data['outgo'] = 2;
            $data['station'] = 3;
            $data['station_id'] = 0;
            $data['station_time'] = 0;
            $huic_test = "<span style='color: #ff0000;'>订单需要回仓，请将商品拿回总仓</span>";

            $map = array("order_id"=>$order_id);

            $re = M('order_info')->where($map)->save($data);

            if(empty($data['shipping_status'])){
                $data['shipping_status'] = M('order_info')->where($map)->getField("shipping_status");
            }
            $a = array (
                'order_id' => $order_id,
                'user_id' => $user_id,
                'order_status' => OS_CONFIRMED,
                'shipping_status' => $data['shipping_status'],
                'pay_status' => PS_PAYED,
                'to_user'=>1,
                'action_note' => "配送员已操作需回仓</br>".$huic_test
            );
            $this->record_diliveryman_log ( $a ); // 记录配送员操作日志

            if($re){
                M('warehouse_deliver_order_group')->where($map)->delete();
                returnApiSuccess(null,'操作成功,商品需拿回总仓11');
            }else{
                returnApiError('change fail:');
            }
        }
    }

    public function order_station(){
        $order_id = I("post.order_id"); //多个ID 以,分割
        $this->orders_station($order_id);
    }


    /**
     * todo 操作订单到站
     * @param $order_id 订单ID
     */
    public function orders_station($order_id=null){
        if(empty($order_id)){
            $order_id = I("post.order_id_list"); //多个ID 以,分割
        }
        $user_id = I("post.user_id");

        //$deploy_info = $this->get_admin_user_name($user_id);

        if(empty($order_id)){
            returnApiError('订单ID为空');
        }else{
            //修改已到站
            $data['station'] = 1;
            $data['station_id'] = $user_id;
            $data['station_time'] = gmtime();

            //条件
            $order_id_array = explode(",",$order_id);
            $map['order_id'] = array("in",$order_id_array);
            $map['outgo'] = 1;  //已出仓
            $map['station'] = 0;    //未到站
            $map['order_status'] = array("neq",2);    //订单为取消
            $map['196_admin_id'] = 0;    //订单为取消

            $re = M('order_info')->where($map)->save($data);

            if($re){
                foreach ($order_id_array as $value){
                    $order_s = M('order_info')->where(array("order_id"=>$value))->
                    field("shipping_status,order_status,pay_status")->find();
                    $a = array (
                        'order_id' => $value,
                        'user_id' => $user_id,
                        'order_status' => $order_s['order_status'],
                        'shipping_status' => $order_s['shipping_status'],
                        'pay_status' => $order_s['pay_status'],
                        'to_user'=>1,
                        'action_note' => "订单已到站"
                    );
                    $this->record_diliveryman_log ( $a ); // 记录配送员操作日志
                    $this->record_logistics($value,$order_s['shipping_status'],"已到站");
                }
                returnApiSuccess(null,'操作成功');
            }else{
                $order_s = M('order_info')->where(array("order_id"=>$order_id))->
                field("outgo,station,shipping_status,order_status")->find();
                if($order_s['outgo']!=1){
                    returnApiError('订单还未出仓');
                }
                if($order_s['station']!=0){
                    returnApiError('订单已经到站');
                }
                if($order_s['order_status']==0){
                    returnApiError('订单已取消');
                }
            }
        }
    }

    /**
     * todo 再次发送收货验证码
     */
    public function distribute_re_verif_code(){
        $user_id = I("post.user_id");
        $order_id = I("post.order_id");

        $where['order_id']=$order_id;
        $where['pay_status']=array("in","2,3");
        $where['order_status']=array("neq","2");

        $shipping_order = M('order_info')->field("order_sn,mobile,mobile,user_id,shipping_status,pay_status,best_time_start,best_time")
            ->where($where)->find();
        if($shipping_order){
            if($shipping_order['shipping_status']!=1){
                returnApiError("订单不在配送中");
            }else{
                $a=array(
                    'order_id'=>$order_id,
                    'user_id'=>$user_id,
                    'order_status'=>5,
                    'shipping_status'=>1,
                    'pay_status'=>$shipping_order['pay_status'],
                    'to_user'=>1,
                    'action_note'=>'再次重新发送收货验证码'
                );

                $this->record_diliveryman_log($a);//记录配送员操作日志

                //生成收货验证码

                $remark['code'] =  $this->get_order_receipt_code($order_id);;


                $remark['phone'] = M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('phone');

                //初始化时区，解决时区不正确的问题

                $datetime = date("Y-m-d",$shipping_order['best_time_start']);

                $remark['best_time'] = $datetime.' '.date("H:i:s",$shipping_order['best_time_start']).'-'.date("H:i:s",$shipping_order['best_time']);

                $wechat_param=array();

                switch($_SERVER['SERVER_NAME']){
                    case 'api.xian3.com':
                        $thisurl='xian3.com';
                        break;
                    case 'api.test.shidexian.com':
                        $thisurl='test.shidexian.com';
                        break;
                    case 'api.shidexian.com':
                        $thisurl='w.shidexian.com';
                        break;
                    default:
                        $thisurl='w.shidexian.com';
                        break;
                }
                $oid=$shipping_order['user_id'];
                $Code=md5($oid.'sdx@9999');

                $goods_name=M("order_goods")->where(array('order_id'=>$order_id,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->limit(1)->getField("goods_name");
                $goods_number=M("order_goods")->where(array('order_id'=>$order_id,'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$order_id.')')))->count();


                $name = M('warehouse_personnel')->where(array('uid'=>$user_id))->getField('name');

                $wechat_param['url']="https://".$thisurl."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$order_id."&utm_source=GZHshipping_start_notice";
                $wechat_param['first']='尊敬的'.$shipping_order['consignee'].'，您所订购的'.$goods_name.'等'.$goods_number.'件商品已经在配送中，预计到达时间为'.$remark['best_time'].'，请保持手机畅通。';
                $wechat_param['keyword1']=$shipping_order['order_sn'];
                $wechat_param['keyword2']=$name;
                $wechat_param['keyword3']=$remark['phone'];
                $wechat_param['remark']=array("您的订单收货码为：[ ".$remark['code']." ],确认收货时请将此码提供给配送员。如代收，请把该码提供给代收人","#FF0000");

                $send_status = A("Smsapi")->send_message_api('receipt_verification',$shipping_order['mobile'],$shipping_order['consignee'],0,$shipping_order['order_sn'],0,$shipping_order['user_id'],$remark,'',$wechat_param);
                if($send_status){
                    returnApiSuccess(null,"成功发送");
                }else{
                    returnApiError("发送失败");
                }
            }
        }else{
            returnApiError("订单已取消/不存在");
        }

    }

    /**
     * 生成收货验证码
     * @param null $order_id
     * @return mixed|string
     */
    public function get_order_receipt_code($order_id=null){
        //生成收货验证码
        if(empty($order_id)){
            $order_id = I("post.order_id");
        }
        if(empty($order_id)){
            returnApiError("订单ID为空");
        }

        $order_verif_code = M('order_verif_code');
        $verif_code = $order_verif_code->where(array("order_id"=>$order_id))->getField("code");
        if($verif_code){
            return $verif_code;
        }else{
            $ver_code = getSmsCode();
            $sms_data['order_id'] = $order_id;
            $sms_data['code'] = $ver_code;
            M("order_verif_code")->add($sms_data);
            return $ver_code;
        }
    }

    /**
     * 送达未确认  无需收货码 可提交 必须照片
     */
    public function distributed_un(){
        $user_id=I('post.user_id','intval');
        $order_id=I('post.order_id','intval');

        if(!isset($user_id) || !isset($order_id)){
            returnApiError('参数错误');
        }
        $this->check_user($user_id);

        $where['order_id']=$order_id;
        $where['196_admin_id']=0;
        $where['pay_status']=array("in","2,3");
        $where['order_status']=array("neq","2");
        $where['shipping_status']=1;

        $list=M('order_info')->field('order_id,order_sn,wid,user_id,order_status,shipping_status,pay_status,mobile,consignee,order_amount,money_paid,surplus,best_time')->where($where)->find();
        if($list['order_id']){
            try {
                if($_FILES['photo']['size']>100){
                    $path= "uploads/refund_pic/".rand(10000000,99999999).".".end(explode('.', $_FILES['photo']['name']));
                    Ali_ossApi::upload($path, $_FILES['photo']['tmp_name']);
                }else{
                    returnApiError("需要上传凭证");
                }
                $data['order_status']=5;
                $data['shipping_status']=6;
                $data['done_photo']=$path;
                $data['confirm_time']=gmtime();
                $data['wp_userid']=$user_id;
                $id=M('order_info')->where($where)->save($data);
                if($id!=false){
                    $is_shipping_status = M("order_action")->where(array("order_id"=>$order_id,"shipping_status"=>array("in","2,6")))->count();
                    if($is_shipping_status==0){
                        $this->order_buckle_inventory($list);
                    }


                    $a=array(
                        'order_id'=>$list['order_id'],
                        'user_id'=>$user_id,
                        'order_status'=>5,
                        'shipping_status'=>6,
                        'pay_status'=>$list['pay_status'],
                        'to_user'=>1,
                        'action_note'=>I('post.remark').'//配送完成,等待客服确认'
                    );
                    $this->record_diliveryman_log($a);//记录配送员操作日志
                    $this->record_logistics($order_id,6,"已代收");


                    $wechat_param=array();

                    switch($_SERVER['SERVER_NAME']){
                        case 'api.xian3.com':
                            $thisurl='xian3.com';
                            break;
                        case 'api.test.shidexian.com':
                            $thisurl='test.shidexian.com';
                            break;
                        case 'api.shidexian.com':
                            $thisurl='w.shidexian.com';
                            break;
                        default:
                            $thisurl='w.shidexian.com';
                            break;
                    }
                    $oid=$list['user_id'];
                    $Code=md5($oid.'sdx@9999');
                    $goods_name=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->limit(1)->getField("goods_name");
                    $goods_number=M("order_goods")->where(array('order_id'=>$list['order_id'],'goods_id'=>array('EXP','not in(select goods_id from sdx_refund_detail where order_id='.$list['order_id'].')')))->count();

                    $louxiaoer_info=A("Smsapi")->get_louxiaoer_info($list['order_id']);

                    if(!empty($louxiaoer_info['name']) && !empty($louxiaoer_info['phone'])){
                        $housekeeper="";
                    }else{
                        $housekeeper="";
                    }

                    //收货超时红包
                    $overtimeBonus='';
                    $overtimeBonusMessage='';
                    $thirtyMinutes=1800;//秒
                    $bonusNote='';
                    if(strtotime("now")>$list['best_time']+$thirtyMinutes && false==true){
                        $overtimeBonus="订单配送超时给您带来不便，特赔付5元超时红包至您账户，请查收！";
                        $overtimeBonusMessage="订单超时特赔付5元红包至您账户，";
                        $record_id=D("Payment")->recharge_bonus($list['user_id'],C("BONUS_APOLOGIZE"));

                        if(!empty($record_id)){
                            $bonusNote.=' 超时配送返红包//红包序列号：'.implode(",",$record_id);
                        }


                    }


                    $wechat_param['url']="https://".$thisurl."/?index&oid=".$oid."&code=".$Code."&lll=#!/ordInfo?ordId=".$list['order_id']."&utm_source=GZHorder_finish";
                    $wechat_param['first']='尊敬的'.$list['consignee'].',您所订购的'.$goods_name.'等'.$goods_number.'件商品已经成功送达。'.$overtimeBonus;
                    $wechat_param['keyword1']=$list['order_sn'];
                    $wechat_param['keyword2']=sprintf("%.2f",($list['order_amount']+$list['money_paid']+$list['surplus']));
                    $wechat_param['keyword3']=date("Y-m-d H:i:s");
                    $wechat_param['remark']=$housekeeper;

                    //发送订单配送完成短信给收货人
                    $send_result = A("Smsapi")->send_message_api('order_finish',$list['mobile'],$list['consignee'],0,$list['order_sn'],0,$list['user_id'],array('overtimeBonus'=>$overtimeBonusMessage),'',$wechat_param);
                    $this->insert_ready_sendmsg_order($list);
                    
                    returnApiSuccess(array('id'=>$id),'收货确认');

                }else{
                    returnApiError('收货失败');
                }
            }catch (Exception $e){
                returnApiErrorExample($e->getMessage());
            }

        }else{
            returnApiError('查无此订单/订单状态不正常');
        }
    }
}